[英]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.
这是可行的,但是,当未选中输入单选类型时,else语句删除背景色是无效的。
Have tried various different ways but cannot get the else statement to fire when you click a different input. 尝试了各种不同的方法,但是当您单击其他输入时无法触发else语句。
HTML: 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: 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/ 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. 问题是因为您有两个具有相同
id
属性的元素-它们必须是唯一的。
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. 要解决此问题,请使用一个类来对单选按钮进行分组,然后使用
this
关键字引用change
事件处理程序中的元素。 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. 请注意应删除内联样式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.