1

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.

2 Answers 2

5

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

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

1 Comment

you can replace first line in $('[id^=check]').click(function() {
0

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

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.