html提供两个选择框radio(单选且必选一个)、checkbox(多选可以不选),但是我想实现一个只能选中一个时且可以不选时的功能时,会发现两个功能都不好用,这是后就需要自己写代码控制了。我觉得有两种方案
1 单选框radio可取消选中
<input type="radio" name="aa" onclick="if(this.c==1){this.c=0;this.checked=0}else this.c=1" c="0">
jquery方法
<input type="radio" name="aa" onclick="chk();">
<script language=javascript>
function chk()
{
document.all.aa.checked=false;
}
</script>
2 多选框checkbox实现只能选中一个
<div class="use_redpackets_content" id="oneCheck">
<ul class="use_redpackets_nav">
<li>
<input type="checkbox" name="oneBox" value=""/>
</li>
<li>
<input type="checkbox" name="oneBox" value=""/>
</li>
<li>
<input type="checkbox" name="oneBox" value=""/>
</li>
</ul>
</div>
<script type="text/javascript">
$(function () {
var fanxiBox = $("#oneCheck input:checkbox");
fanxiBox.click(function () {
if(this.checked || this.checked=='checked'){
fanxiBox.removeAttr("checked");
//这里需注意jquery1.6以后必须用prop()方法
//$(this).attr("checked",true);
$(this).prop("checked", true);
}
});
});
</script>
3遍历div下的checkbox查看选中个数
<div class="use_redpackets_content" id="oneCheck">
<ul class="use_redpackets_nav">
<li>
<input type="checkbox" name="oneBox" value=""/>
</li>
<li>
<input type="checkbox" name="oneBox" value=""/>
</li>
<li>
<input type="checkbox" name="oneBox" value=""/>
</li>
</ul>
</div>
<script type="text/javascript">
function checkedValue(){
var num=;
var fanxiBox=$("#oneCheck input:checkbox");
fanxiBox.each(function(){
if ($(this).is(':checked')) {
alert($(this).val());
num++;
}
alert(num);
});
}
</script>