简体   繁体   中英

jQuery radio button checked, else statement not working

I want an input to change its styles (add background color) when checked. This is working, however, the else statement to remove the background color when the input radio type isn't checked is not working.

Have tried various different ways but cannot get the else statement to fire when you click a different input.

HTML:

<tr style="color:white;">
<td id="test" style="background-color:rgb(153, 117, 82);" value="1">
<label><input type="radio" name="c0" class="c0" value="10" onclick="output();" id="t"/>1</label>
</td>
</tr>

<tr style="color:white;">
<td style="background-color: rgb(255, 57, 57);">
<label><input type="radio" name="c0" class="c0" value="20" onclick="output();" id="t"/>2</label>
</td>

JS:

$('input#t').on("click", function() {
if ($("input#t").is(':checked')) {
    $(this).parent().addClass("active");
} 
    else {
    $(this).parent().removeClass("active");
}
});

codepen: https://codepen.io/Not_A_Fax_Machine/pen/zzRMNZ/

The problem is because you have two elements with the same id attribute - they must be unique.

To fix the problem use a class to group the radio buttons, then use the this keyword to reference the element within the change event handler. Try this:

 $('.t').on("change", function() { $('label').removeClass('active'); $(this).parent().toggleClass('active', this.checked); // output(); }); 
 tr { color: white; } td.foo { background-color: rgb(153, 117, 82); } td.bar { background-color: rgb(255, 57, 57); } .active { background-color: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td class="foo"> <label><input type="radio" name="c0" class="t c0" value="10" />1</label> </td> </tr> <tr> <td class="bar"> <label><input type="radio" name="c0" class="t c0" value="20" />2</label> </td> </tr> </table> 

Note the removal of the inline styles, which should be avoided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM