JQuery: Multiple checkbox to disable multiple textbox
I have multiple checkbox in my form; each to disable a specific textbox.
Currently I have this in my form.
$("#check1").click(function() {
$("#text1").attr('disabled',! this.checked)
});
$("#check2").click(function() {
$("#text2").attr('disabled',! this.checked)开发者_如何转开发
});
...
...
...
Any tips on how I can shorten this up? I think having 1 line of code for each checkbox and textbox seems to be too much, repetitive and redundant. Thank you in advance.
You can do this:
$("#check1, #check2, #check3").click(function() {
var textId = "#" + this.id.replace("check", "text");
$(textId).attr('disabled',! this.checked)
});
Or
$(":checkbox[id^=check]").click(function() {
var textId = "#" + this.id.replace("check", "text");
$(textId).attr('disabled',! this.checked)
});
...provided that you don't have any checkboxes whose IDs start with "check" that you don't want included in the selector.
Basically, any selector that will identify the checkboxes in question will work, and then it's just a matter of manipulating the ID.
Update: It may be that you can do away with IDs entirely, depending on your HTML structure. For instance, given this form:
<form id='foo'>
<label><input type='checkbox'>Field 1</label>
<br><input type='text' size='40' disabled>
<br><label><input type='checkbox'>Field 2</label>
<br><input type='text' size='40' disabled>
<br><label><input type='checkbox'>Field 3</label>
<br><input type='text' size='40' disabled>
<br><label><input type='checkbox'>Field 4</label>
<br><input type='text' size='40' disabled>
</form>
...we can achieve the desired effect like this:
$("#foo input[type=checkbox]").click(function() {
var next = $(this).parent().nextAll('input[type=text]:first');
next.attr("disabled", !this.checked);
});
Live example
If you can change your HTML structure, you can do this:
$(".check").click(function() {
var index = $(this).index(".check");
$(".text:eq("+index+")").attr('disabled',! this.checked)
});
精彩评论