天天看點

checkbox的隻能選中一個,div下checkbox的周遊

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>