jQuery

Enable or Disable Button based on condition using jQuery

In this article we will learn Enable or Disable Button based on condition using jQuery.

This article will explain how to enable the Button when text is entered name in TextBox and disable the Button when the TextBox is empty using jQuery.

HTML Code
This article will explain how to enable the Button when text is entered name in TextBox and disable the Button when the TextBox is empty using jQuery.
The HTML contains of one TextBox and a Button. The HTML Button has been assigned disabled using the disabled attribute.

Enter Name:
<input type=”text” id=”txtName” />
<hr />
<input class=”button” type=”button” value=”Submit” disabled=”disabled” />

Enable or Disable Button based on condition using jQuery

Inside the jQuery document ready event handler, the TextBox has been assigned with a jQuery OnKeyUp event handler.
When User enter a value in TextBox, the Button is enabled and if the TextBox is empty, the Button is disabled using jQuery.

<script type=”text/javascript” src=”https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js”></script>
<script type=”text/javascript”>
$(function () {
$(“#txtName”).keyup(function () {
//Reference the Button.
var btnSubmit = $(“.button”);

//Verify the TextBox value.
if ($(“#txtName”).val().trim() != “”) {
//Enable the TextBox when TextBox has value.
btnSubmit.removeAttr(“disabled”);
} else {
//Disable the TextBox when TextBox is empty.
btnSubmit.attr(“disabled”, “disabled”);
}
});
});
</script>

Complete Code

<!DOCTYPE html>

<html lang=”en” xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta charset=”utf-8″ />
<title></title>

<script type=”text/javascript” src=”https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js”></script>
<script type=”text/javascript”>
$(function () {
$(“#txtName”).keyup(function () {
//Reference the Button.
var btnSubmit = $(“.button”);

//Verify the TextBox value.
if ($(“#txtName”).val().trim() != “”) {
//Enable the TextBox when TextBox has value.
btnSubmit.removeAttr(“disabled”);
} else {
//Disable the TextBox when TextBox is empty.
btnSubmit.attr(“disabled”, “disabled”);
}
});
});
</script>
<style>
.button {

border: none;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
</head>
<body>

Enter Name:
<input type=”text” id=”txtName” />
<hr />
<input class=”button” type=”button” value=”Submit” disabled=”disabled” />

</body>
</html>

Output

enable-or-disable-button-based-on-condition-using-jquery

enable-or-disable-button-based-on-condition-using-jquery

Leave a Reply

Your email address will not be published.