tags:

views:

3963

answers:

4

I've got a form with several search (text) fields. When text is entered into one of the fields, I'd like to disable the others. Conversely, if all text is removed from the active text field, the other fields should be re-enabled.

The basic idea would be something like this (I think):

$(document).ready(function() {
    $("input[@type=text]").keypress(function(e) {
        if(current textbox has text in it)
        {
            //disable all textboxes that aren't this one
        }
        else
        {
            //enable all textboxes
        }
    });
});

I'm not clear on what the easiest way to find/work with "all text boxes that aren't this one" is.

A: 

Use the not selector

yoavf
+3  A: 

I think the best way to do "all textboxes that aren't this one" is using the not filter like:

$(document).ready(function() {
    $(":text").keyup(function(e) {
        if($(this).val() != '') {
            $(":text").not(this).attr('disabled','disabled');
        } else {
            $(":text").removeAttr('disabled');
        }
    });
});

Couple notes:

  • I recommend giving a class to all the input elements you want to include with this behavior and doing a selector of input.myfields as it is faster/cleaner.
  • Also, as of jQuery 1.3, the @ in the selector is not supported. :text is shorthand for what you want, if are you sticking to selecting them that way.
  • I also think you want the keyup event instead of keypress.
Paolo Bergantino
@type has been deprecated for a while, and no longer works in 1.3. :text is far more concise.
Adam Lassek
I said that it is deprecated in my answer...
Paolo Bergantino
And it hasn't really been "a while"
Paolo Bergantino
Well, since 1.2. It has been removed completely from 1.3, so I wouldn't use it in an example.
Adam Lassek
Ok, well, I updated my answer with :text for posterity's sake.
Paolo Bergantino
+2  A: 

I would just disable them all first, and then since the code to be executed is triggered by an event for the control, you can use the this keyword to reference the control with focus and re-enable it.

$("input[@type=text]").attr("disabled", true);
$(this).attr("disabled", false);
Josh Stodola
+1  A: 

I'd attach the login to the focus/blur events instead:

$(function() {
    $(':text').focus(function() {
        $(':text').not(this).attr('disabled','disabled');
    }).blur(function {
        if (this.value.length == 0) {
            $(':text').removeAttr('disabled');
        }
    });
})

@attr selectors were deprecated in 1.2, and have been removed completely from 1.3. In this case you'll want to use :text

Adam Lassek