如何将选中的复选框一次限制为一个

How to limit the checked checkboxes to just one at a time?

本文关键字:一次 一个 复选框      更新时间:2023-09-26

我正在尝试使用复选框创建一个过滤器。我一次只需要选中一个复选框。我该怎么做呢?

场景:页面有一个手表目录。用户希望根据男士或女士来筛选手表

下面是我的代码:

$("#filter-options :checkbox").click(function() 
	{
       	$(".collection-wrapper .strap-wrapper").hide();
       	$("#filter-options :checkbox:checked").each(function() 
       	{
           $("." + $(this).val()).fadeIn();
		});
       
        if($('#filter-options :checkbox').filter(':checked').length < 1) 
        {
        	$(".collection-wrapper .strap-wrapper").fadeIn();
        	
        }
        
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Filter Items</h3>
<ul id="filter-options">
  <li><input type="checkbox" value="filter_man" data-filter_id="man"> Man</li>
  <li><input type="checkbox" value="filter_woman" data-filter_id="woman"> Woman</li>
</ul>
<div class="collection-wrapper">
  <div class="strap-wrapper filter_man">
    <h2>man</h2>
    <p></p>
  </div>
  <div class="strap-wrapper filter_woman">
    <h2>woman</h2>
    <p></p>
  </div>
  <div class="strap-wrapper filter_man filter_woman">
    <h2>man / woman</h2>
    <p></p>
  </div>
  <div class="strap-wrapper filter_woman">
    <h2>woman</h2>
    <p></p>
  </div>
</div>

提前感谢!

复选框用于选择多个选项的值。您需要的是单选按钮。它们正是为此目的而使用的。一次只能选择一个单选按钮。所以将你的代码替换为:

<ul id="filter-options">
  <li><input type="radio" name="filter" value="filter_man" data-filter_id="man"> Man</li>
  <li><input type="radio" name="filter" value="filter_woman" data-filter_id="woman"> Woman</li>
</ul>

示例如下: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio

单选按钮就是你要找的;)

看看这些链接:

jQuery api demo

小提琴例子HTML:

<form id="myForm">
<input type="radio" name="myRadio" value="1" /> 1 <br />
<input type="radio" name="myRadio" value="2" /> 2 <br />
<input type="radio" name="myRadio" value="3" /> 3 <br />
</form>

JS

$('#myForm input').on('change', function() {
   alert($('input[name="myRadio"]:checked', '#myForm').val()); 
});

你可以使用单选按钮或者你可以这样做:

$('input[type=checkbox]').change(function(){
   if ($('input[type=checkbox]:checked').length > 1) {
        this.checked = false;
   }
})

你可以只使用单选按钮,但如果你想用复选框,解决方案是相当简单的。

当你点击其中一个复选框时,选中所有的复选框并删除"已选中"状态,然后只添加已选中的复选框

像这样:

    // On checkbox click
    $("#filter-options input[type=checkbox]").click(function(event) {
        // Uncheck all checkboxes
        $("#filter-options input[type=checkbox]").prop("checked", false);
        // Check that one that you clicked
        $(this).prop("checked", true)
    });