user1633322
user1633322

Reputation: 83

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);
    });

});

Upvotes: 0

Views: 162

Answers (2)

Mike
Mike

Reputation: 637

To Start, I think it would be smart to add a unique class to the inputs that you care about. this way you can do something along the lines of:

$('.yourClass').on('input', function() {
  var x = true;
  $('.yourClass').each(function() {
    this = $(this); //cast it to jQuery obj (ez ref)
    if (this.val() == "")
            x = false;
  } );
} );

Basically, every time someone enters something into the fields, jQuery will iterate through your inputs checking the values and adding 1 to x. If x is equal to the number of elements you are checking then it will enable the button.

This is not the most elegant solution but how I got around the same issue you were having when I was rushed into finishing a project.

Modified my answer with what @JaredT mentioned about the boolean, far more elegant. I am sure this could be improved further though, hope this gets the ball rolling.

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129792

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);

Upvotes: 1

Related Questions