A-A+

js multiple全选与取消全选实现代码

2016年01月28日 前端设计 暂无评论 阅读 5 views 次

本文章总结了利用jquery与js实现multiple全选与取消全选代码有需要参考的朋友可参考参考,代码如下:

  1. $("select").change(function(){  
  2.     var n = $(this).children().length;  
  3.     var obj;  
  4.     var i = 1;  
  5.        $(this).children().each(function(){  
  6.      if(i == n)  
  7.      {  
  8.       alert($(this).text());  
  9.      }  
  10.      i++;  
  11.     });  
  12.    });  

综合以上二法,本人轻易得出了自己想要的效果,如下:

  1. function selectall()  
  2. {  
  3.  $("select").children().each(function(){$(this).attr("selected","selected")})  
  4. }  

分别用到了 children()和$(this).attr("selected","selected")

一个js用法:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
  5. <script type="text/javascript">  
  6. <!--  
  7. function selectAll()  
  8. {  
  9.  var opts=document.getElementById("CourseList");  
  10.  for(var i=0;i<opts.length;i++)  
  11.  {  
  12.   opts[i].selected=true;  
  13.  }  
  14. }  
  15. //-->  
  16. </script>  
  17. </head>  
  18. <body>  
  19. <select id="CourseList" name="CourseList" multiple="multiple" size="20" style="width:230px;">   
  20. <option value="003" >(003) 消费者行为与销售心理</option>   
  21. <option value="004" >(004) 产品策划与市场推广</option>   
  22. <option value="005" >(005) 品牌定位与广告原理</option>   
  23. </select>   
  24. <input type="button" onclick="selectAll()" value="全选">   
  25. </form>  
  26. </body>  
  27. </html>  
标签:

给我留言