这是我的div
<div id="extras">
<div class="col-md-12" id="extra-Material">
<div class="form-group"><label>Material</label>
<br
><label class="checkbox-inline mr10">
<input name="ffp[]" type="checkbox" value="1_1"> Fabric</label>
<label class="checkbox-inline mr10"><input name="ffp[]" type="checkbox" value="1_2"> Wood</label>
</div>
</div>
<div class="col-md-12" id="extra-Color">
<div class="form-group"><label>Color</label><br><label class="checkbox-inline mr10"><input name="ffp[]"
type="checkbox"
value="2_8">
Brown</label><label class="checkbox-inline mr10"><input name="ffp[]" type="checkbox" value="2_5">
Red</label></div>
</div>
</div>
目前我有 2 个内部 div extra-Material
和 extra-Color
。这些基本上是动态生成的。所有这些附加的 div 内部都有相同的复选框名称 ffp[]
。我想要 1 次选中 1 个复选框。假设我点击“Fabric”,然后点击“Wood”,它应该只取消选择 Fabric(第一个 div 内 id = extra-Material
内的所有复选框)应该取消选中,然后应该取消选中 Wood被检查。与第二个 div 类似,依此类推。我已经搜索过,有代码可以取消选择页面上的所有复选框,但我不想要这样。有人可以帮助我吗?
这是我的 JS 代码
if (json_data.length > 0) {
var html = '';
html += '<div class="col-md-12" id="extra-' + name + '">'
html += '<div class="form-group">';
html += '<label>' + name + '</label>';
html += '<br>';
json_data.forEach(function (entry) {
html += '<label class = "checkbox-inline mr10" >';
html += '<input name="ffp[]" type = "checkbox" value = "' + val + '_' + entry.ffp_id + '"> ' + entry.en_name + '';
html += '</label>';
});
html += '</div>';
html += '</div>';
$('#extras').append(html);
}
最佳答案
您必须将 change
事件处理程序绑定(bind)
到input
DOM 元素。
此外,使用 .closest()
方法可以从当前集合中获取所有输入元素。
您应该使用.on
方法来绑定(bind)动态添加的元素的事件处理程序。
事件委托(delegate)允许我们将单个事件监听器附加到父元素,该事件监听器将为匹配选择器的所有后代触发,无论这些后代现在存在还是将来添加。
了解有关事件委托(delegate)的更多信息 here
$(document).on('change', 'input[type="checkbox"]', function(){
$(this).closest('.col-md-12').find('input[type="checkbox"]').prop('checked',false);
$(this).prop('checked',true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="extras">
<div class="col-md-12" id="extra-Material">
<div class="form-group"><label>Material</label>
<br
><label class="checkbox-inline mr10">
<input name="ffp[]" type="checkbox" value="1_1"> Fabric</label>
<label class="checkbox-inline mr10"><input name="ffp[]" type="checkbox" value="1_2"> Wood</label>
</div>
</div>
<div class="col-md-12" id="extra-Color">
<div class="form-group"><label>Color</label><br><label class="checkbox-inline mr10"><input name="ffp[]"
type="checkbox"
value="2_8">
Brown</label><label class="checkbox-inline mr10"><input name="ffp[]" type="checkbox" value="2_5">
Red</label></div>
</div>
</div>
关于javascript - 取消选择特定 div 内除选中的复选框之外的所有复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46558667/