tdc
tdc

Reputation: 5464

how to toggle multiple inputs within a table depending on radio button selection

Assume the following html:

<tr>
    <td>
        <label for="c1_testRdio">Have you taken any tests in this class?:</label>
        <br>
        <label>Yes<input type="radio" class="testRdio" name="c1_testRdio" value="Yes"></label>
        <label>No <input type="radio" class="testRdio" name="c1_testRdio" value="No" checked></label>
        <label>How Many? <input type="text" class="howManyTests" name="c1_howManyTests" disabled></label>
    </td>
    <td>
        <label for="c1_whatGradesTests">What were your grades?:</label><br>
        <input type="text" name="c1_whatGradesTests" disabled>
    </td>
</tr>

if radio with value="Yes" is selected, what jQuery (1.5 compatible ) code would enable the 2 text inputs, c1_howManyTests and c1_whatGradesTests?

Have tried:

$('.testRdio').change(function(){
    //var txt = $(this).closest("td").next("td").children('.howManyTests');
    var txt = $(this).parent().next('label>input[type="text"]');
    console.log(txt.id);
    this.value == 'No' ? txt.removeAttr('disabled') : txt.attr('disabled', 'disabled');
});

Upvotes: 0

Views: 263

Answers (3)

PSL
PSL

Reputation: 123739

Try this:

$('.testRdio').change(function () {
    $(this).closest('tr').find('input[type="text"]').attr('disabled', this.value === 'No');
});

The older jq version that doesnot have prop, attr (used to do the job of prop as well) used to take bool values for disabled.

Demo

Also i had to fix your markup a lot as well (Now i see its fixed in the question already)

Upvotes: 1

Scott Rowell
Scott Rowell

Reputation: 1130

Your code was a little messy, so I rebuilt it: http://jsfiddle.net/QgJac/1/

I think hiding the whole div is better. They don't really need to see those questions if they select 'No'.

Upvotes: 0

j08691
j08691

Reputation: 207901

$('.testRdio').change(function(){
   $(this).closest('tr').find('input[type="text"]').attr('disabled',$(this).val()=="No");
});

jsFiddle example

Upvotes: 0

Related Questions