I'm attempting to disable a submit button untill the user has filled out the input fields in the form.
I found THIS thread here which had a really good answer. I'm having just a little problem getting the submit button the re-enable when the fields are filled out.
Can someone please take a look at this function and help me figure out what I'm missing? Any help would be greatly appreciated :D Thank you.
Heres a Fiddle also
$(document).ready(function() {
var $submit = $("input[type=submit]");
if ( $("input:empty").length > 0 ) {
$submit.attr("disabled","disabled");
} else {
$submit.removeAttr("disabled");
}
});
<form method="POST" action="<%=request.ServerVariables("SCRIPT_NAME")%>">
User Name: <input name="Username" type="text" size="14" maxlength="14" /><br />
Password: <input name="last_name" type="password" size="14" maxlength="14"><br />
<input type="submit" value="Login" name="Submit" id="loggy">
</form>
Just click f12 in your browser, find the submit button in the html, and then remove the disabled ! It will submit the form even if the inputs are empty.
$('#enabled'). click(function () { if ($('#submit-button').is(':disabled')) { $('#submit-button'). removeAttr('disabled'); } else { $('#submit-button'). attr('disabled', 'disabled'); } });
1.1 To disable a submit button, you just need to add a disabled attribute to the submit button. $("#btnSubmit"). attr("disabled", true); 1.2 To enable a disabled button, set the disabled attribute to false, or remove the disabled attribute.
One of the most used logic related to submitting a form is preventing sumbission if a field is empty. In this example we'll provide examples with source code how to prevent form submit in case of empty field. The main trick here is using . preventDefault() function to stop the submission.
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=password]');
function checkEmpty() {
// filter over the empty inputs
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});
Working sample
Instead of blur you can also use keyup like:
$inputs.on('keyup', function() {
$submit.prop("disabled", !checkEmpty());
}).keyup(); // trigger an initial keyup
Also you can combine multiple events:
$inputs.on('keyup blur', function() {
$submit.prop("disabled", !checkEmpty());
}).keyup(); // trigger any one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With