santa
santa

Reputation: 12512

Disable all form elements but one

I use the following to disable all form elements within a table row:

$(".chkbx").change(function(){
    var $this  = $(this);
    if ($this.is(":checked")) {
        $this.closest("tr").find(":input").attr("disabled", false);
    } else {
        $this.closest("tr").find(":input").attr("disabled", true);
    }
});

Which it does great. The problem -- it disables ALL, including .chkbx. I need to keep the checkbox with this class (chkbx) always enabled. How do I exclude it from the function?

Upvotes: 1

Views: 2983

Answers (4)

David Thomas
David Thomas

Reputation: 253496

I'd suggest something like the following:

$('.chkbx').change(
    function(){
        if ($(this).is(':checked')){
$(this).closest('tr').find('input,textarea,select').not($(this)).attr('disabled',true);
        }
        else {
$(this).closest('tr').find('input,textarea,select').not($(this)).attr('disabled',false);
        }
    });

Upvotes: 0

Adam Rackis
Adam Rackis

Reputation: 83376

I think using the not function like this would work

$this.closest("tr").find(":input").not(".chkbx").attr("disabled", true);

Upvotes: 4

Arthur Neves
Arthur Neves

Reputation: 12148

how about this:

$(".chkbx").change(function(){
    var $this  = $(this);
    if ($this.is(":checked")) {
        $this.closest("tr").find(":input").attr("disabled", false);
    } else {
        $this.closest("tr").find(":input:not(.chkbx)").attr("disabled", true);
    }
});

not sure if it will work! but give it a try!

Upvotes: 0

Paul
Paul

Reputation: 2206

Add one more line to your existing code:

$(".chkbx").change(function(){
    var $this  = $(this);
    if ($this.is(":checked")) {
        $this.closest("tr").find(":input").attr("disabled", false);
    } else {
        $this.closest("tr").find(":input").attr("disabled", true);
    }
    $this.attr("disabled",false);
});

It's not optimal or efficient, but it should work.

Upvotes: 1

Related Questions