开发者

Disabling/enabling a button based on multiple other controls using Javascript/jQuery

I have a bunch of controls:

Disabling/enabling a button based on multiple other controls using Javascript/jQuery

When a user clicks the Generate button, a fu开发者_JS百科nction uses all of the values from the other controls to generate a string which is then put in the Tag text box.

All of the other controls can have a value of null or empty string. The requirement is that if ANY of the controls have no user entered value then the Generate button is disabled. Once ALL the controls have a valid value, then the Generate button is enabled.

What is the best way to perform this using Javascript/jQuery?


This can be further optimized, but should get you started:

var pass = true;

$('select, input').each(function(){
    if ( ! ( $(this).val() || $(this).find(':selected').val() ) ) {
        $(this).focus();
        pass = false;
        return false;
    }
});

if (pass) {
    // run your generate function
}

http://jsfiddle.net/ZUg4Z/

Note: Don't use this: if ( ! ( $(this).val() || $(this).find(':selected').val() ) ).
It's just for illustration purposes.


This code assumes that all the form fields have a default value of the empty string.

$('selector_for_the_parent_form')
  .bind('focus blur click change', function(e){

    var
      $generate = $('selector_for_the_generate_button');

    $generate.removeAttr('disabled');

    $(this)
      .find('input[type=text], select')
        .each(function(index, elem){  
          if (!$(elem).val()) {
            $generate.attr('disabled', 'disabled');
          }
        });

  });

Basically, whenever an event bubbles up to the form that might have affected whether the generate button ought to be displayed, test whether any inputs have empty values. If any do, then disable the button.

Disclaimer: I have not tested the code above, just wrote it in one pass.


If you want the Generate button to be enabled as soon as the user presses a key, then you probably want to capture the keypress event on each input and the change event on each select box. The handlers could all point to one method that enables/disables the Generate button.

function updateGenerateButton() {
    if (isAnyInputEmpty()) {
        $("#generateButton").attr("disabled", "disabled");
    } else {
        $("#generateButton").removeAttr("disabled");
    }
}

function isAnyInputEmpty() {
    var isEmpty = false;
    $("#input1, #input2, #select1, #select2").each(function() {
        if ($(this).val().length <= 0) {
            isEmpty = true;
        }
    });
    return isEmpty;
}

$("#input1, #input2").keypress(updateGenerateButton);
$("#select1, #select2").change(updateGenerateButton);

The above assumes that your input tags have "id" attributes like input1 and select2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜