koenHuybrechts
koenHuybrechts

Reputation: 878

Disable input field when checkbox toggled (JQuery)

I have a list of checkboxes and with every checkbox, there is an input field. If I check the checkbox, the inputfield has to be disabled. Example:

Checkbox 1 - Input 1
Checkbox 2 - Input 2
Checkbox 3 - Input 3

The real code:

<table id="food" width="580px">
    <tr>
        <th colspan="5">Eten</th>
        <tr>
            <td><input type="checkbox" name="checkbox_1_1" value="" /></td>
            <input type="hidden" name="todo_1_1" value="7" />
            <td>Braadworst</td>
            <td>7</td>
            <td><input type="text" name="item_1_1" size="4" value="" /></td>
            <td></td>
        </tr>
        <tr>
            <td><input type="checkbox" name="checkbox_1_2" value="" /></td>
            <input type="hidden" name="todo_1_2" value="5" />
            <td>Witte worst</td>
            <td>5</td>
            <td><input type="text" name="item_1_2" size="4" value="" /></td>
            <td></td>
        </tr>
    </tr>
</table>

Only the input field with the same number may be disabled ...

Through Google I found: http://techchorus.net/disable-and-enable-input-elements-div-block-using-jquery

The example works perfectly, but is there a way to do this without pre-defining the names? In my case, it is impossible to know the names, so they have to be determined when toggling the checkbox, no?

Any suggestions?

Upvotes: 1

Views: 6271

Answers (2)

Nick Craver
Nick Craver

Reputation: 630587

A few corrections to the markup first: that hidden input needs to be inside a <td> and the header row needs a closing </tr>, then you can do this:

​$('#food').delegate(':checkbox', 'change', function(​​​​​​​​​​​​​​​​​) {
    $(this).closest('tr').find('input:text').attr('disabled', !this.checked);
});
$(':checkbox').change(); //set state initially

You can see a demo here, we're using .closest() to get up to the <tr>, then finding inputs of [type=text] using .find() and :text.

Upvotes: 4

Reigel Gallarde
Reigel Gallarde

Reputation: 65274

if you have this "very" simple structure

<input type="checkbox" name="" /><input type="text" name="" />
<input type="checkbox" name="" /><input type="text" name="" />
<input type="checkbox" name="" /><input type="text" name="" />
<input type="checkbox" name="" /><input type="text" name="" />
<input type="checkbox" name="" /><input type="text" name="" />​

you can

$(':checkbox').change(function(){
  $(this).next().attr('disabled',!this.checked);
})​;

here is a demo

but then I know you don't have that "very" simple structure so, read the following and get the idea from above...

  1. traversing
  2. selectors

If you can provide the structure of your html, much better...

Upvotes: 6

Related Questions