使复选框的行为像使用javascript的单选按钮 [英] make checkbox behave like radio buttons with javascript
问题描述
我需要使用javascript来操纵复选框的行为。他们应该基本上像单选按钮(一次只能选择一个,加上取消选择任何以前的选择)。
问题是我不能使用普通单选按钮第一个地方,因为每个单选按钮的名称属性会不同。
我知道它不是让苹果看起来像梨子的最终和最闪亮的解决方案,而w3c不会给我们拇指但它现在比改变整个cms结构的核心php逻辑更好了 - )
任何帮助都非常值得赞赏!
HTML:
< label>< input type =checkboxname =cb1class =chb/> CheckBox1< /标签>
< label>< input type =checkboxname =cb2class =chb/> CheckBox2< /标签>
< label>< input type =checkboxname =cb3class =chb/> CheckBox3< /标签>
< label>< input type =checkboxname =cb4class =chb/> CheckBox4< /标签>
jQuery:
< code $(。chb)。change(function(){
$(。chb)。prop('checked',false);
$(this).prop ('checked',true);
});
如果您希望用户可以取消选中所选项目:
$(。chb)。change(function(){
var checked = $(this).is(':checked');
$(.chb)。prop('checked',false);
if(checked){
$(this).prop('checked',true);
}
});
演示:
http://jsfiddle.net/44Zfv/724/
I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() {
$(".chb").prop('checked', false);
$(this).prop('checked', true);
});
if you want user can unchecked selected item :
$(".chb").change(function() {
var checked = $(this).is(':checked');
$(".chb").prop('checked',false);
if(checked) {
$(this).prop('checked',true);
}
});
Demo :
http://jsfiddle.net/44Zfv/724/
这篇关于使复选框的行为像使用javascript的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!