复选框当单选按钮使用

    平时会遇到本来是单选的项,用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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章