Was wondering if anyone could point me in the right direction with the following piece of jquery. I want to disable the submit button until my input fields have been filled in.
I have come up with this
$(document).ready(function (){
if ($('#inputName, #inputEmail, #inputTel').val().length > 0) {
$("input[type=submit]").attr("disabled", "false");
}
else {
$("input[type=submit]").attr("disabled", "true");
}
});
but the button is permanently disabled, Even after filling in all the text input fields
Still learning Jquery and haven't used it for a while.. So any pointers appreciated
Thanks
How do you disable submit button until all fields are filled? 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.
You never disable it if the length is 0.
Enable / Disable submit button 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.
Your event binding is only on document ready.
So there is no listener when you change something.
Do this instead :
$(document).ready(function (){
validate();
$('#inputName, #inputEmail, #inputTel').change(validate);
});
function validate(){
if ($('#inputName').val().length > 0 &&
$('#inputEmail').val().length > 0 &&
$('#inputTel').val().length > 0) {
$("input[type=submit]").prop("disabled", false);
}
else {
$("input[type=submit]").prop("disabled", true);
}
}
Your current code is fine, but doesn't respond to user events, which is where you're tripping.
$('#inputName, #inputEmail, #inputTel').keyup(function(){
if($(this).val().length > 0){
$("input[type=submit]").prop("disabled", false);
}else{
$("input[type=submit]").prop("disabled", true);
}
});
Edit actually, this won't work. because one of those elements will caus ethe submit button to become enabled, regardless of the other ones. I'll hotfix momentarily.
Edit Here's the rough draft fix, it could probably be prettier, but will definitely be a good starting point.
var toValidate = $('#inputName, #inputEmail, #inputTel'),
valid = false;
toValidate.keyup(function () {
if ($(this).val().length > 0) {
$(this).data('valid', true);
} else {
$(this).data('valid', false);
}
toValidate.each(function () {
if ($(this).data('valid') == true) {
valid = true;
} else {
valid = false;
}
});
if (valid === true) {
$('input[type=submit]').prop('disabled', false);
}else{
$('input[type=submit]').prop('disabled', true);
}
});
And here's your jsFiddle illustrating this method
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