SpaghettiMonster
SpaghettiMonster

Reputation: 620

Using jQuery to reference form fields in an Array

I have an HTML form that looks something like this:

<td><input type='checkbox' id='a[] '><input type='text' id='b[]'></td>
<td><input type='checkbox' id='a[] '><input type='text' id='b[]'></td>

Within a jQuery function I would like to enable / disable the associated input text input - b when the checkbox is clicked.

I am unsure how I can reference each field individually within a jQuery .click() function when using an array.

Any help would be much appreciated!

Upvotes: 0

Views: 482

Answers (4)

Derek
Derek

Reputation: 589

Similar concept to Thomas, but executes on page load and throws in a .focus() for good measure:

$(function(){
    var toggleState = function(){
        if($(this).is(':checked'))
            $(this).next('[name="b"]').removeAttr('disabled').focus();
        else
             $(this).next('[name="b"]').attr('disabled','disabled');
    };
   //bind event and fire off on page load
    $('input[name="a"]').bind('click',toggleState).each(toggleState);
})

Also, you shouldn't have duplicate ids... use the name attribute or target by classes.

<table>
 <tr><td><input type='checkbox' name='a'><input type='text' name='b'></td></tr>
 <tr><td><input type='checkbox' name='a'><input type='text' name='b'></td></tr>
</table>

http://jsfiddle.net/R28dV/4/

Upvotes: 2

gilly3
gilly3

Reputation: 91487

Remove the disabled attribute to enable an input. Set the disabled attribute to any value, customarily "disabled", to disable an input. Setting disabled="" is not good enough, the mere presence of the attribute disables the input. You have to remove the attribute.

$("input[type=checkbox]").click(function()
{
    if (this.checked) $(this).next().removeAttr("disabled");
    else $(this).next().attr("disabled", "disabled");
});

Upvotes: 1

Thomas Shields
Thomas Shields

Reputation: 8942

Try this (i'm sure there's a more concise way but i don't have IntelliSense in here lol)

$("checkbox").click(function(){
 if($(this).next().attr("disabled") == "disabled") {
$(this).next().attr("disabled", "");
}
else {
$(this).next().attr("disabled", "disabled");
}
});

Upvotes: 1

Chris Cherry
Chris Cherry

Reputation: 28554

Your HTML is invalid if you have duplicate IDs. Give them unique IDs so your HTML is valid again, and your problem is also solved.

Upvotes: 0

Related Questions