In this article I will explain with an example, how to enable or disable Button based on condition using JavaScript.
This article will illustrate how to enable the Button when text is entered in TextBox and disable the Button when the TextBox is empty using JavaScript.
HTML Markup
The HTML Markup consists of an HTML TextBox and a Button. The HTML Button has been assigned disabled using the disabled attribute.
The TextBox is assigned OnKeyUp event handler. When User inputs a value in TextBox, the EnableDisable JavaScript function gets called.
Passport Number:
<input type="text" id="txtPassportNumber" onkeyup="EnableDisable(this)" />
<hr />
<input id="btnSubmit" type="button" value="Submit" disabled="disabled" />
Enable or Disable Button based on condition using JavaScript
When User inputs a value in TextBox, first the Button is referenced. Then the value of the TextBox is checked.
If the TextBox has value, the Button is enabled and if the TextBox is empty, the Button is disabled using JavaScript.
<script type="text/javascript">
function EnableDisable(txtPassportNumber) {
//Reference the Button.
var btnSubmit = document.getElementById("btnSubmit");
//Verify the TextBox value.
if (txtPassportNumber.value.trim() != "") {
//Enable the TextBox when TextBox has value.
btnSubmit.disabled = false;
} else {
//Disable the TextBox when TextBox is empty.
btnSubmit.disabled = true;
}
};
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads