jquery - 在一组中只选择一个复选框

标签 jquery html

我需要在 html 中只选择一组中的一个复选框。 我找到了我的榜样。但是我无法意识到。它不起作用。 这是我的例子:example

这是我的 HTML 代码:

    <div>
            <li>
                <div class="radio">
                    <label>
                    <input type="checkbox" name="mobil[1][]" id="optionsRadios1" value="1" checked class="radi">
                    Сотовый телефон имеется
                    </label>
                </div>
            </li>
            <li>
                <div class="radio">
                    <label>
                    <input type="checkbox" name="mobil[1][]" id="optionsRadios2" value="0" class="radi">
                    Сотовый телефон не имеется
                    </label>
                </div>
            </li>
    <div>

和代码jquery:

$("input:checkbox").on('click', function() {
        // in the handler, 'this' refers to the box clicked on
        var $box = $(this);
        if ($box.is(":checked")) {
        // the name of the box is retrieved using the .attr() method
        // as it is assumed and expected to be immutable
        var group = "input:checkbox[name='" + $box.attr("name") + "']";
        // the checked state of the group/box on the other hand will change
        // and the current value is retrieved using .prop() method
        $(group).prop("checked", false);
        $box.prop("checked", true);
   } 
   else {
        $box.prop("checked", false);
   }
});

请帮忙。

最佳答案

$(function(){
				
		$("input[name='fruit[]']").change(function(e) {
			if($('input[name="fruit[]"]:checked').length==1) {
				$("input[name='fruit[]']:not(:checked)").attr("disabled", true);
			} else {
				$("input[name='fruit[]']:not(:checked)").attr("disabled", false);
			}
		});		
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
<head>

</head>
<body>
	<form>		
		
	   <input type="checkbox" name="fruit[]" value="orange"> Orange
       <input type="checkbox" name="fruit[]" value="apple"> Apple
       <input type="checkbox" name="fruit[]" value="grapefruit"> Grapefruit
       <input type="checkbox" name="fruit[]" value="banana"> Banana
       <input type="checkbox" name="fruit[]" value="watermelon"> Watermelon
	   <input type="checkbox" name="fruit[]" value="watermelon"> Papaya 
	</form>
	
</body>
</html>

关于jquery - 在一组中只选择一个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29389971/

相关文章:

html - Chrome 中的垂直元素符号对齐方式?

html - 如何使用 CSS 将文本垂直对齐到彩色 div 中?

jquery - ColorPicker 绑定(bind)颜色

jquery - 使用 jQuery 触发 RadMenu Dropdown 操作

javascript - Jquery 悬停效果在 IE 中不起作用

javascript - 如何在使用 javascript 出错时重新加载页面?

javascript - 在视口(viewport)上检测

jquery - 如何使 ul 之前的文本在 html 中以单行显示?

javascript - 使用 Web 服务没有响应?

javascript 验证带空格的长度