Search code examples
jquerykeyup

Checking two fields for entering characters


I have two fields and a button. Task: the button is inactive until characters are entered in both fields. If at least one field is empty - the button is inactive.

Field id: «zipcode-from» and «zipcode-to»

I have the following code:

jQuery('input#zipcode-button').attr('disabled','disabled');
jQuery('input#zipcode-from').keyup(function(){
    if (jQuery('input#zipcode-from').val() == "") {
        jQuery('input#zipcode-button').attr('disabled','disabled');
    }
    else
    {
        jQuery(':input#zipcode-button').removeAttr('disabled');
    }
})

It works for the first field. But how to check both fields? Tried &&, but I can not make this function true.


Solution

  • you could just use css syntax to attach the keyup to both fields, then check if one of the fields is empty (you should use OR here). Something like this:

    jQuery('input#zipcode-button').attr('disabled','disabled');
    jQuery('input#zipcode-from, input#zipcode-to').keyup(function(){
    if ((jQuery('input#zipcode-from').val() == "")||(jQuery('input#zipcode-to').val() == "")) {
        jQuery('input#zipcode-button').attr('disabled','disabled');
    }
    else
    {
        jQuery(':input#zipcode-button').removeAttr('disabled');
    }
    })