Home > Web Front-end > JS Tutorial > body text

Implement functions such as selecting all check boxes, inverting selections, and deselecting all check boxes based on jquery

高洛峰
Release: 2017-02-06 13:10:22
Original
895 people have browsed it

jquery implements functions such as selecting all, inverting selection, and not selecting all. The following is an example. Assume that the page has the following set of check boxes and several related buttons (select all, inverse select, unselect all, etc.):

<input type="checkbox" name="fruit" value="apple" />苹果
<input type="checkbox" name="fruit" value="orange" />橘子
<input type="checkbox" name="fruit" value="banana" />香蕉
<input type="checkbox" name="fruit" value="grape" />葡萄
  
<input type="button" id="btn1" value="全选">
<input type="button" id="btn2" value="全不选">
<input type="button" id="btn3" value="反选">
<input type="button" id="btn4" value="选中所有奇数">
<input type="button" id="btn5" value="获得选中的所有值">
Copy after login

then implement related functions respectively. The complete code is as follows:

$(function(){
  $(&#39;#btn1&#39;).click(function(){//全选
    $("[name=&#39;fruit&#39;]").attr(&#39;checked&#39;,&#39;true&#39;);
  });
  $(&#39;#btn2&#39;).click(function(){//全不选
    $("[name=&#39;fruit&#39;]").removeAttr(&#39;checked&#39;);
  });
  $(&#39;#btn3&#39;).click(function(){//反选
    $("[name=&#39;fruit&#39;]").each(function(){
      if($(this).attr(&#39;checked&#39;)){
        $(this).removeAttr(&#39;checked&#39;);
      }else{
        $(this).attr(&#39;checked&#39;,&#39;true&#39;);
      }
    })
  });
  $("#btn4").click(function(){//选中所有奇数
    $("[name=&#39;fruit&#39;]:even").attr(&#39;checked&#39;,&#39;true&#39;);
  })
  $("#btn5").click(function(){//获取所有选中的选项的值
    var checkVal=&#39;&#39;;
    $("[name=&#39;fruit&#39;][checked]").each(function(){
      checkVal+=$(this).val()+&#39;,&#39;;
    })
    alert(checkVal);
  })
});
Copy after login

Note that the jquery package must be introduced before using jquery!

The above is the code that the editor has worked hard to compile. Is it very convenient to use? I hope it can help everyone.

For more related articles on how to implement checkbox selection, inverse selection, and deselecting all based on jquery, please pay attention to the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!