2012-12-06 27 views
11

我有HTML项目,4例如:jQuery。如何取消除此之外的所有复选框(这是选中)

<div> 
    <div><input type="checkbox" class="foo"> Checkbox</div> 
    <div><input type="checkbox" class="foo"> Checkbox</div> 
    <div><input type="checkbox" class="foo"> Checkbox</div> 
    <div><input type="checkbox" class="foo"> Checkbox</div> 
    <div><input type="checkbox" class="foo"> Checkbox</div> 
    <div><input type="checkbox" class="foo"> Checkbox</div> 
</div> 

而现在,我想未来:如果我点击任何复选框 - 复选框应检查及其他复选框应该取消选中。我该怎么做?

+1

你想叫一个单选按钮...... – RRikesh

+0

@弗朗索瓦·瓦尔,没有什么问题!我不知道这件事。 – Andrew

回答

23

您可以通过name属性使用radio按钮,并将它们组合。如果你有checkboxes做到这一点,那么你可以这样来做,

Live Demo

$('.foo').click(function(){  
     $('.foo').attr('checked', false); 
     $(this).attr('checked', true);   
}); 

对于动态生成的HTML你需要on,让您与静态父母委托的情况下,你可以与你一起使用文件不知道静态父项。

$(document).on('click','.foo', function(){  
     $('.foo').attr('checked', false); 
     $(this).attr('checked', true);   
}); 

如果文档已知,则可以用静态父代替文档。例如如果格包含动态生成的ID是parentdiv那么你可以有

`$('#parentdiv').on('click','.foo', function(){` 

编辑

使用prop而不是attr房产checkedselected,或disabled按文档。

从jQuery 1.6开始,对于尚未设置的属性 ,.attr()方法返回undefined。要检索和更改DOM属性(如 )表单元素的选中状态,选中状态或禁用状态,请使用 .prop()方法。

+0

非常感谢您的回答。我知道'radiobutton'组。但我无法使用它,因为我的Spring MVC控制器必须具有不同的名称参数。由于这个原因,我决定使用复选框和JavaScript – Andrew

+21

+1:用于工作解决方案和DEMO。一般来说,一行代码可能是:'$('。foo')。not(this).attr('checked',false);' – Nope

+0

Thanks @FrançoisWahl,建议声明非常好。 – Adil

0

这里有点我碰巧工作:

.siblings("input[type='checkbox']").attr("checked", true); 

将选择除了被点击了一个所有复选框。

$("input[type=checkbox]").on("click", function() { 
 

 
    if ($(this).val() == "none") { 
 
    
 
    $(this).siblings("input[type=checkbox]").attr('checked', false); 
 
    
 
    } else { 
 
    
 
    $(this).siblings("input[value=none]").attr('checked', false); 
 

 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 

 
    <input type="checkbox" id="worker-soft-eaglesoft" checked><label for="worker-soft-eaglesoft">&nbsp;Eaglesoft</label><br> 
 
    <input type="checkbox" id="worker-soft-dentrix"><label for="worker-soft-dentrix">&nbsp;Dentrix</label><br> 
 
    <input type="checkbox" id="worker-soft-softDent"><label for="worker-soft-softDent">&nbsp;Soft-Dent</label><br> 
 
    <input type="checkbox" id="worker-soft-denticon"><label for="worker-soft-denticon">&nbsp;Denticon</label><br> 
 
    <input type="checkbox" id="worker-soft-other"><label for="worker-soft-other">&nbsp;Other</label><br> 
 

 
    <input type="checkbox" id="worker-soft-none" value="none"> 
 
    <label for="worker-soft-none">&nbsp;No Software Experience - Paper Records Only</label><br> 
 
</div>

相关问题