Bas Bas - 7 months ago 7
HTML Question

Radio box enabling input fields with JQuery

I'm trying to enable a textfield based on which option is chosen in a radio button. I'm just really new to any javascript or jquery, so I really need some help.

This is the TR from a table where the radio buttons and input fields are placed

<tr>
<td><b>Yes or no?</b></td>
<td><input id="yes" type="radio" name="choose" value="yes"> Yes</td>
</tr>
<tr>
<td></td>
<td><input id="no" type="radio" name="choose" value="no" checked> No</td>
</tr>

<tr>
<td>
<input type="text" name="disabledtextfield" id="test" disabled />
<script type="text/javascript">
$('#no').click(function () {
$('#test').removeAttr("disabled");
});

$('#yes').click(function () {
$('#test').attr("disabled", "disabled");
});
</script>
</td>
</tr>


The problem is probably really trivial, but again, I haven't worked with this at all. Any help would be appreciated!

Answer

You can do it like like following using change event instead of click.

$(':radio[name=choose]').change(function () {
    var isChecked = $('#yes').is(':checked');
    $('#test').prop("disabled", !isChecked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td><b>Yes or no?</b></td>
        <td><input id="yes" type="radio" name="choose" value="yes"> Yes</td>
    </tr>
    <tr>
        <td></td>
        <td><input id="no" type="radio" name="choose" value="no" checked> No</td>
    </tr>

    <tr>
        <td>
            <input type="text" name="disabledtextfield" id="test" disabled />
        </td>
    </tr>
</table>