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 clic开发者_如何学JAVAked.
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!
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/
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");
}
});
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");
});
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.
精彩评论