JQuery Disable/Enable Submit Button
I Have This Html: How Can I Do Something Like This: When the Text Field Is Empty the Submit Should Be Disabled (Disabled="Disabled"). When Something Is Typed...
I have this HTML:
<input type="text" name="textField" />
<input type="submit" value="send" />
How can I do something like this:
- When the text field is empty the submit should be disabled (disabled="disabled").
- When something is typed in the text field to remove the disabled attribute.
- If the text field becomes empty again(the text is deleted) the submit button should be disabled again.
I tried something like this:
$(document).ready(function(){
$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').change(function(){
if($(this).val != ''){
$('input[type="submit"]').removeAttr('disabled');
}
});
});
…but it doesn't work. Any ideas?
21 Answers
The problem is that the change event fires only when focus is moved away from the input (e.g. someone clicks off the input or tabs out of it). Try using keyup instead:
$(document).ready(function() {
$(':input[type="submit"]').prop('disabled', true);
$('input[type="text"]').keyup(function() {
if($(this).val() != '') {
$(':input[type="submit"]').prop('disabled', false);
}
});
});
$(function() {
$(":text").keypress(check_submit).each(function() {
check_submit();
});
});
function check_submit() {
if ($(this).val().length == 0) {
$(":submit").attr("disabled", true);
} else {
$(":submit").removeAttr("disabled");
}
}
This question is 2 years old but it's still a good question and it was the first Google result ... but all of the existing answers recommend setting and removing the HTML attribute (removeAttr("disabled")) "disabled", which is not the right approach. There is a lot of confusion regarding attribute vs. property.
Must Read
HTML
The "disabled" in <input type="button" disabled> in the markup is called a boolean attribute by the W3C.