Home  >  Article  >  Web Front-end  >  checkbox全选以及反选/取消全选

checkbox全选以及反选/取消全选

WBOY
WBOYOriginal
2016-06-01 09:54:591536browse
<code>

<script src="jquery-1.3.2.min.js" type="text/javascript"></script>


<input type="checkbox" name="chk_list" id="chk_list_1" value="1">1<br>
<input type="checkbox" name="chk_list" id="chk_list_2" value="2">2<br>
<input type="checkbox" name="chk_list" id="chk_list_3" value="3">3<br>
<input type="checkbox" name="chk_list" id="chk_list_4" value="4">4<br>
<input type="checkbox" name="chk_all" id="chk_all">全选/取消全选
<script type="text/javascript">
$("#chk_all").click(function(){
     $("input[name='chk_list']").attr("checked",$(this).attr("checked"));
});
</script>

</code>


jQuery.attr  获取/设置对象的属性值,如:

<code>$("input[name='chk_list']").attr("checked");     //读取所有name为'chk_list'对象的状态(是否选中)
$("input[name='chk_list']").attr("checked",true);      //设置所有name为'chk_list'对象的checked为true</code>


再如:

<code>$("#img_1").attr("src","test.jpg");    //设置ID为img_1的<img  alt="checkbox全选以及反选/取消全选" >src的值为'test.jpg'
$("#img_1").attr("src");     //读取ID为img_1的<img  alt="checkbox全选以及反选/取消全选" >src值</code>


下面的代码是获取上面实例中选中的checkbox的value值:

<code> <script type="text/javascript">
    //获取到所有name为'chk_list'并选中的checkbox(集合)
    var arrChk=$("input[name='chk_list]:checked");
    //遍历得到每个checkbox的value值
    for (var i=0;i<arrChk.length;i++)
    {
         alert(arrChk[i].value);
    }
</script></code>


或者使用jquery的each

<code><script type="text/javascript">
    var arrChk=$("input[name='chk_list']:checked");
    $(arrChk).each(function(){
       window.alert(this.value);                        
    }); 
});
</script></code>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn