0

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!

4 Answers 4

2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Cheers Derek. I have since changed it to targed by class. I noticed you removed the [] from the name, which is my biggest problem. Is it possible to do this while still using the array?
Yeah, if you are going to target by class you can keep the name as an array. You can probably target by the name attribute with the array brackets, but I believe it's more efficient to target by class name anyways. Check original jsfiddle link for updated code to utilize class targeting http://jsfiddle.net/R28dV/4/
1

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");
}
});

Comments

1

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");
});

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.