Monday, February 21, 2011

JQuery Select Input Fields Except Hidden

I have a row in a table which contains a checkbox and some other form fields (text boxes, hidden fields, select lists). When the checkbox is checked I want to disable all form fields in that row except for the hidden fields. I have this working for the most part, but I can't seem to ignore the hidden fields.

What is the best way to select all form fields in a table row but ignore hidden fields in the selection?

From stackoverflow
  • .........

    $('tr input').attr('disabled', true)
    $('tr input[type="hidden"]').removeAttr('disabled')
    
  • Assuming by "hidden" you mean type="hidden" ie:

    <input type="hidden" name="foo" value="bar">
    

    then you can use the attribute not equals selector to do this:

    $("tr input:checkbox").click(function() {
      var cb = $(this);
      var tr = $(this).closest("tr");
      if (cb.val()) {
        tr.find("input[type!='hidden']").attr("disabled", true);
      } else {
        tr.find("input[type!='hidden']").removeAttr("disabled");
      }
    });
    

    My general advice is avoid attribute selectors. They're slow. Give the relevant inputs (either the hidden ones or the not hidden ones) a class and then use that in the selectors.

    If however you mean "hidden" as in "not visible" then use the :visible selector:

    $("tr input:checkbox").click(function() {
      var cb = $(this);
      var tr = $(this).closest("tr");
      if (cb.val()) {
        tr.find("input:visible").attr("disabled", true);
      } else {
        tr.find("input:visible").removeAttr("disabled");
      }
    });
    
    Pointy : @Cletus do you think that a filter() call with a function that checked whether "this.type" is "hidden" would be faster than the in-selector attribute test?
    Bob : Ahhh, never even thought of tagging them with a class. Nice!
  • First, you need to tag your "selector" checkbox (e.g. with a class attribute "selector) so that it is clear that it is used for checking instead of regular form element. Then you use this:

    $('table :checkbox.selector').click(function(ev) {
        $(ev.currentTarget)
                .parents('td').siblings('td')
                .find(':input:not([type=hidden])')
                .attr('disabled', ev.currentTarget.checked);
    });
    

    This solution works for all inputs (eg. select lists, textareas) and it doesn't disable the selector checkbox itself.

    I'm assuming you use latest jQuery.

0 comments:

Post a Comment