zoukankan      html  css  js  c++  java
  • 统计选中的复选框的个数

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>jquery test</title>
    <script src="jquery-1.11.1.min.js"></script>
    </head>
    
    <body>
      <input type="checkbox" name="check" value="one"/>one<br/>
      <input type="checkbox" name="check" value="two"/>two<br/>
      <input type="checkbox" name="check" value="three"/>three<br/>
      <input type="checkbox" name="check" value="four"/>four<br/>
      <input type="checkbox" name="check" value="five"/>five<br/>
      <input type="checkbox" name="check" value="six"/>six<br/>
      <input type="checkbox" name="check" value="seven"/>seven<br/>
      <button name="sub">提交</button>
    <script type="text/javascript">
    	$("button[name=sub]").click(function(){
    		var len = $("input:checkbox:checked").length;
    		alert("你一共选中了"+len+"个复选框");
    	})
    </script>
    </body>
    </html>
    

    使用选择器得到全部被勾选的复选框元素的集合,然后通过推断元素的个数来得到用户勾选的个数。


    有的时候,我们还对用户勾选复选框的个数做了限制,如果仅仅能勾选三个,对应的代码是这种:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>jquery test</title>
    <script src="jquery-1.11.1.min.js"></script>
    </head>
    
    <body>
      <input type="checkbox" name="check" value="one"/>one<br/>
      <input type="checkbox" name="check" value="two"/>two<br/>
      <input type="checkbox" name="check" value="three"/>three<br/>
      <input type="checkbox" name="check" value="four"/>four<br/>
      <input type="checkbox" name="check" value="five"/>five<br/>
      <input type="checkbox" name="check" value="six"/>six<br/>
      <input type="checkbox" name="check" value="seven"/>seven<br/>
    <script type="text/javascript">
    	$("input:checkbox").click(function(){
    		var len = $("input:checkbox:checked").length;
    		if(len>3){
    			alert('亲。最多仅仅能选三个哟~');
    			return false;	//另刚才勾选的取消
    		}
    	})
    </script>
    </body>
    </html>
    


  • 相关阅读:
    LeetCode 461. Hamming Distance
    LeetCode 442. Find All Duplicates in an Array
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode Find the Difference
    LeetCode 415. Add Strings
    LeetCode 445. Add Two Numbers II
    LeetCode 438. Find All Anagrams in a String
    LeetCode 463. Island Perimeter
    LeetCode 362. Design Hit Counter
    LeetCode 359. Logger Rate Limiter
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/6881392.html
Copyright © 2011-2022 走看看