平時會遇到本來是單選的項,用radio是可以進行單選,但需要取消選中項時,除非自己代碼進行控制不然無法取消選中,在這種前提下個人更傾向使用checkbox來實現單選。故特地分享下checkbox實現單選的js代碼。
1.加入如下js代碼:
<script type="text/javascript">
//複選框單選
$("td[isOnly='only']").find(":checkbox").each(function(){
$(this).click(function(){
if($(this).attr("checked")){
$(this).parent().find(":checkbox").removeAttr('checked');
$(this).attr('checked','checked');
}
});
});
</script>
<td isOnly="only">
<input type="checkbox" id="box1"><label for='box1'>測試1</label>
<input type="checkbox" id="box2"><label for='box2'>測試2</label>
</td>