How to disable a button in JavaScript based on condition

Set button disable property flase for disbaled it and true for enabled it in JavaScript. You have to use id for that and if-else conditions statement.

How to disable a button in JavaScript based on condition Example

In the example, we have 2 input fields first for text and the second one is for the button. When the user types something button will enable it. Default the submit button remains disabled

See the code output where disable attribute changing Boolean value on text input.

<html>
<body>
    <input type="text" id="txt" onkeyup="manage(this)" />

    <input type="submit" id="btSubmit" disabled value="Submit" />
</body>
<script>
    function manage(txt) {
        var bt = document.getElementById('btSubmit');
        if (txt.value != '') {
            bt.disabled = false;
        }
        else {
            bt.disabled = true;
        }
    }
</script>
</html>

Output: If the TextBox has value, the Button is enabled and if the TextBox is empty, the Button is disabled using JavaScript.

disable a button in JavaScript based on condition

Do comment if you have any doubts or suggestions on this question topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.