javascript - limiting checkbox checks via jquery or javascript
问题描述
I have a twitter boosttrap Q and A style quiz with options, and I would like to limit the number (variable) of answers for this.
This codepen does a good job of explaining the problem: https://codepen.io/vjandrei/pen/rAuam
However, I would like to restrict this to a set of name
attributes. So instead of:
<input type="checkbox" class="check" name="check1" id="check1" >
<label class="layout" for="check1"></label>
<input type="checkbox" class="check" name="check2" id="check2" >
<label class="layout" for="check2"></label>
<input type="checkbox" class="check" name="check3" id="check3" >
<label class="layout" for="check3"></label>
Id like the Jquery to operate only on checkbox
with a certain name attribute (because there are other checkboxes in the page with different name attribite):
<input type="checkbox" class="check" name="ok" id="check1" >
<label class="layout" for="check1"></label>
<input type="checkbox" class="check" name="ok" id="check2" >
<label class="layout" for="check2"></label>
<input type="checkbox" class="check" name="ok" id="check3" >
<label class="layout" for="check3"></label>
and I would like to write something like this in Jquery:
$("input:checkbox[name="ok"]").click(function() {
var bol = $("input:checkbox[name="ok"]:checked").length >= 2;
$("input:checkbox[name="ok"]").not(":checked").attr("disabled",bol);
});
However the above ^ does not work for me (apologies, new to JQuery here).. and I was wondering how I can restrcit the selection of checkboxes restrcited to elements with certain names.
解决方案
您需要使用其name
属性限定复选框,以便在运行事件处理程序时仅计算给定组中的复选框。请注意,由于[name="ok"]
包含双引号,因此您需要将选择器作为一个整体放入单引号中。此外,对于名称不同的组(例如check1
,在您的第一个片段中) check2
,您需要在egcheck3
上使用“开头为”选择器:name
name^="check"
$('input:checkbox[name^="check"]').click(function() {
var bol = $('input:checkbox[name^="check"]:checked').length >= 2;
$('input:checkbox[name^="check"]').not(":checked").attr("disabled", bol);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check" name="check1" id="check1">
<label class="layout" for="check1"></label>
<input type="checkbox" class="check" name="check2" id="check2">
<label class="layout" for="check2"></label>
<input type="checkbox" class="check" name="check3" id="check3">
<label class="layout" for="check3"></label>
推荐阅读
- python - 不使用 while 循环将文本设置为 qlineedit
- netlogo - 我有两种雏菊和两种兔子:如何让一种颜色的兔子只吃一种颜色的雏菊?
- scala - akka http mock(授权)指令
- javascript - 是否可以为 webapp 提供浏览器包装器?
- reactjs - 搜索并获取有关 ReactJs 中每个值的信息
- python - 如何在进程之间共享多维数组?
- javascript - AJAX 按钮消失
- javascript - 隐藏弹出框功能恢复打开的弹出框功能
- intellij-idea - 寻找类似 VS Code Remote Dev Extension Pack 的 IntelliJ Remote Dev 体验
- neo4j - 将比特币区块链导入neo4j - 错误:缺少必需选项'--nodes = [