jquery:如何选择嵌套的radio元素
HTML代码:jquery:如何选择嵌套的radio元素,jquery,Jquery,HTML代码: <div class="poll_all_chs" > {% for ch in poll_obj.get_choices %} <div class="poll_ch"> <span><input type="radio" id="radio_button" name="choice_id" value="{{ch.id}}">{{ch
<div class="poll_all_chs" >
{% for ch in poll_obj.get_choices %}
<div class="poll_ch">
<span><input type="radio" id="radio_button" name="choice_id" value="{{ch.id}}">{{ch.choice}}</span>
</div>
</div>
但是
如何访问单选按钮元素
if($('#radio_button').is(':checked')){
//code here for checked
}
使用下面的代码
Id必须是唯一的。阅读
或
你可以做:
$(".poll_ch span :radio").each(function() {
if (this.checked)
console.log("Im checked!");
});
另外,一个重要的注意事项是,您将使用提供的代码重复ID。解决这个问题,一切都是坏消息。试试这个
$(".poll_ch :radio").each(function() {
if ($(this).prop('checked')==true)
console.log("This radio checked");
});
看起来您正在动态创建具有相同ID的元素。这是一种非常糟糕的做法,会使您的HTML无效,请使ID唯一。我假设这是因为OP正在添加多个具有相同ID的控件,此解决方案是否仍适用于此?我正在循环中添加单选按钮,在这种情况下,如何为单选按钮分配不同的ID
$('input:radio[name="choice_id"]').each(function() {
if (this.checked){
//code here for checked
}
});
$(".poll_ch span :radio").each(function() {
if (this.checked)
console.log("Im checked!");
});
$(".poll_ch :radio").each(function() {
if ($(this).prop('checked')==true)
console.log("This radio checked");
});