user1633322 user1633322 - 3 months ago 10
Javascript Question

enable button when certain text fields have values

I have a form with several text fields and I would like the add button to be enabled when the required fields are filled in. The button is disabled by default in the HTML. In Firebug it appears the blur function fires but the that the if statement isn't reached.

$(".cd-form :input").blur(function(){

var ok=true;
$("#signup-firstnmame,#signup-surname","#signup-Address1","#signup-City","#signup-Postcode","#signup-Email","#signup-Mobile").each(function(){
/* if ($(this).val()==="")*/


if ($('#signup-firstnmame').val() !== "" && $('#signup-surname').val() !== "" && $('#signup-Address1').val() !== "" && $('#signup-City').val() !== "" && $('#signup-Postcode').val() !== "" && $('#signup-Email').val() !== "" && $('#signup-Mobile').val() !== "")
$("#AddData").prop("disabled",false);

else
$("#AddData").prop("disabled",true);
});

});

Answer

The commas are supposed to be a part of the selector, not separate parameters.

$('#signup-firstname, #signup-surname, #signup-Address1, ...

Also, if you're checking all of the fields, as in your if statement, you don't need to do that once for each field, it'll suffice to do it once.

If you would consider adding a class to the relevant fields, your function would be much more readable, i.e:

$('#AddData').prop('disabled', $('.required-field[val=""]').length > 0);
Comments