首页 > 解决方案 > 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.

标签: javascriptjquery

解决方案


您需要使用其name属性限定复选框,以便在运行事件处理程序时仅计算给定组中的复选框。请注意,由于[name="ok"]包含双引号,因此您需要将选择器作为一个整体放入单引号中。此外,对于名称不同的组(例如check1,在您的第一个片段中) check2,您需要在egcheck3上使用“开头为”选择器:namename^="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>


推荐阅读