DivDiff DivDiff - 1 month ago 6
HTML Question

Radio button stays checked after clicking another one

I'm trying to set up a series of radio buttons which will become unchecked after clicking another one, i.e. only one can be checked at a time. I also make a text area below the radio buttons appear or disappear based on which radio button has been selected. My html is

<table id="tableId">
<tbody>
<tr>
<td>
<div id="selectTitle">
Some Select
</div>
<select id="stuff">
<option value="0">option 0</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
</select>
</td>
</tr>
<tr>
<td>
<div>
Radio Options
</div>
<ul>
<li>
<input id="rad1" type="radio" /> rad1 </li>
<li>
<input id="rad2" type="radio" /> rad2 </li>
<li>
<input id="rad2" type="radio" /> rad3 </li>
</ul>
</td>
</tr>
<tr>
<td>
<input id="textArea" type="textarea" />
</td>
</tr>
</tbody>
</table>


and my javascript is

$("#rad1").click(function() {
$("#rad2").prop("checked", false);
$("#rad3").prop("checked", false);
$("#textArea").hide();
});
$("#rad2").click(function() {
$("#rad1").prop("checked", false);
$("#rad3").prop("checked", false);
$("#textArea").hide();
});
$("#rad3").click(function() {
$("#rad1").prop("checked", false);
$("#rad2").prop("checked", false);
$("#textArea").show();
});


Here's the problem:

rad1 and rad2 work correctly. When you click on them, the buttons toggle from being checked to unchecked as expected. However, when you click rad3, it stays checked, and won't become unchecked until you refresh the page. I looked through the cases, and nothing seems to be different between them. Here's a jsfiddle with my code. Any help is appreciated!

Answer

If you give your radio inputs same name, they would work as you uexpect:

<ul>
    <li><input id="rad1" name="rad" type="radio" /> rad1 </li>
    <li><input id="rad2" name="rad" type="radio" /> rad2 </li>
    <li><input id="rad3" name="rad" type="radio" /> rad3 </li>
</ul>
Comments