Skip to content

How to disable a button in JavaScript based on condition

  • by

Set button disable property false for disabled 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 the 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading