javascript jquery 检查所有输入:单击按钮时的复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33828119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:57:35  来源:igfitidea点击:

jquery check all input:checkbox on button click

javascriptjquery

提问by X9DESIGN

Is any can write how to make select/deselect function on button click in jquery?

有没有人可以写如何在jquery中点击按钮时选择/取消选择功能?

<ul style="list-style:none">
    <li>
        <label><input class="checkhour" type="checkbox"> One</label>
    </li>
    <li>
        <label><input class="checkhour" type="checkbox"> Two</label>
    </li>
    <li>
        <label><input class="checkhour" type="checkbox"> Three</label>
    </li>
    <li><button type="button" class="checkall">select/deselect</button></li>
</ul>

I trying do this with couple ways but none of them want to work.

我尝试用几种方法来做到这一点,但他们都不想工作。

回答by Alex Char

You can check previous condition by assign a global variable:

您可以通过分配全局变量来检查先前的条件:

var clicked = false;
$(".checkall").on("click", function() {
  $(".checkhour").prop("checked", !clicked);
  clicked = !clicked;
  this.innerHTML = clicked ? 'Deselect' : 'Select';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul style="list-style:none">
  <li>
    <label>
      <input class="checkhour" type="checkbox">One</label>
    <label>
      <input class="checkhour" type="checkbox">Two</label>
    <label>
      <input class="checkhour" type="checkbox">Three</label>
  </li>
  <li>
    <button type="button" class="checkall">Select</button>
  </li>
</ul>

回答by Andrew Evt

var state = false; // desecelted

$('.checkall').click(function () {

    $('.checkhour').each(function() {
        if(!state) {
            this.checked = true;
        } else {
            this.checked = false;
        }
    });

    //switch
    if (state) {
        state = false;   
    } else {
        state = true;
    }

});

and jsfiddle for you http://jsfiddle.net/0jazurdu/

和 jsfiddle 给你 http://jsfiddle.net/0jazurdu/

回答by Kishore Sahasranaman

you can to get all the input checkboxusing getElementsByTagNameand use the property checked = true

你可以得到所有的input checkbox使用getElementsByTagName和使用属性checked = true

var isChecked = false;
function checkAll() {
    var checkboxes = document.getElementsByTagName('input');
     if (isChecked) {
         for (var i = 0; i < checkboxes.length; i++) {
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = true;
             }
         }
     } else {
         for (var i = 0; i < checkboxes.length; i++) {
             console.log(i)
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = false;
             }
         }
     }
  isChecked = !isChecked;
 }
<ul style="list-style:none">
<li>
    <label><input class="checkhour" type="checkbox"> One</label>
    <label><input class="checkhour" type="checkbox"> Two</label>
    <label><input class="checkhour" type="checkbox"> Three</label>
</li>
<li><button type="button" class="checkall" onClick="checkAll()">select/deselect</button></li>
</ul>

回答by Sourabh T

Hi you have to include jquery in your html script and follow below code for that

嗨,您必须在 html 脚本中包含 jquery 并按照以下代码进行操作

<ul style="list-style:none">
<li>
    <label><input class="checkhour" name="checkme[]" type="checkbox"> One</label>
    <label><input class="checkhour" name="checkme[]" type="checkbox"> Two</label>
    <label><input class="checkhour" name="checkme[]" type="checkbox"> Three</label>
</li>
<li><button type="button" id="selectall" >select/deselect</button></li>
</ul>

Add below jquery script for select all checkboxes.

添加以下 jquery 脚本以选择所有复选框。

    <script type="text/javascript">
    $(document).ready(function() {
        $('#selectall').click(function(event) {  //on click 
            var atLeastOneIsChecked = $('input[name="checkme[]"]:checked').length > 0;
               if(atLeastOneIsChecked){
                 $('.checkhour').each(function() { //loop through each checkbox
                    this.checked = true;  //select all checkboxes   
                 });
               }else{
               $('.checkhour').each(function() { //loop through each checkbox
                   this.checked = false; //deselect all checkboxes                    
            }); 
         }
    });
});
    </script>

回答by Sapna

1) JS:

1)JS:

$(document).ready(function() { 
        var base_url = "<?php echo base_url(); ?>";//alert(base_url);
        $('#inputtype').on('change', function() {
            if (this.value == '1') { 
                $("#groupname").change(function() {     
                  $('#myModal').modal('hide');
                });
            }else if(this.value == '2'){
               $('#checkb').hide();
               $("#groupname").change(function() {

                    var id = $(this).val();
                    if(id!=0){ 
                        $.ajax({ 
                              type: "GET",
                              url: base_url+"groupsms/ajaxdata",
                              // dataType: 'json',
                              data: {groups_id:id},
                              success: function(data) { 
                                   console.log(data);
                                   var obj = JSON.parse(data);


                                        for(var i = 0, len = obj.length; i < len; i++) {
                                            $("#myInput").on("keyup", function() {
                                                $('#checkb').show();
                                                var value = $(this).val().toLowerCase();console.log(value);
                                                $("#myTable #tablerow").filter(function() {
                                                    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
                                                    console.log($(this).toggle($(this).text().toLowerCase().indexOf(value) > -1));
                                                });
                                              });
                                            var checkbox ='<input type="checkbox" id="checkbox" class = "chcktbl"  name="findt" value="'+obj[i].id+'" />';
                                                var temp = '<tr id="tablerow"><td>' + obj[i].id + '</td>';
                                                temp+='<td>' + checkbox + '</td>';
                                                temp+= '<td>' + obj[i].msisdn+ '</td>';
                                                temp+= '<td>' + obj[i].name + '</td>';
                                                $('#tbody').append(temp);
                                        }

                                        var selected = [];
                                        // alert("function");
                                        $('.chcktbl').click(function(event){
                                            var length = $('.chcktbl:checked').length; //alert(length);
                                            if (length > 0) {
                                                // alert("greater");
                                                if($(this).is(':checked')){
                                                    selected.push(this.value);
                                                    //alert(selected);
                                                    $('input[name=hiddeninputname]').val(selected);
                                                }else{
                                                    // alert("not checked");
                                                    selected.pop(this.value);
                                                    $('input[name=hiddeninputname]').val(selected);
                                                }


                                            }


                                        });


                                    $('button#submit').click(function(event){ //alert("HEIII");

                                        if($('[type="checkbox"]').is(":checked")){ 

                                            $('#myModal').modal('hide');
                                            return true;

                                        }
                                        else
                                        {
                                            $('#myModal').modal('show');
                                            $('input[name=hiddeninputname]').val("") ;
                                            $("div#errMsg1").css("color", "red");
                                            $("div#errMsg1").html("Please click on checkbox");
                                            return false;

                                        }
                                    });


                                    $('#checkb').click(function () {
                                        if (this.checked == false) {
                                            $('.chcktbl:checked').attr('checked', false);
                                            for(var j = 0; len1 = selected.length;  j++) {
                                                selected.pop(selected[j]);
                                            }
                                        }
                                        else {
                                            $('tbody > tr:visible .chcktbl:not(:checked)').attr('checked', true);
                                            var length = $('.chcktbl:checked').length; 
                                            var MyChkValue = $('.chcktbl:checked').val(); 

                                            $(".chcktbl:checked").each(function(){

                                                selected.push($(this).val());
                                                $('input[name=hiddeninputname]').val(selected);
                                                // alert(selected);
                                            });


                                        }
                                    });
                                    $('#myModal').modal('show');

                              }
                        });

                    }


                });
            }
        });


    });

2)HTML:

2)HTML:

<div class="modal-body" id="employee_detail">
                           <table style="width: 100%" border="1" style="text-align:center">
                                 <thead>
                                      <tr>
                                           <th>ID</th>
                                           <th>Select All
                                                <?php $numberCheck = array( 'name' => 'checkb', 'id' => 'checkb','required'=>'required', 'value' => '', 'checked' => set_checkbox('checkb', 'checkb')); ?>
                                                <?php echo form_checkbox($numberCheck); ?>
                                           </th>

                                           <th>Number</th>
                                           <th>Name</th>
                                       </tr>
                                 </thead>
                                 <tbody id="tbody">
                                 </tbody>
                            </table>
                        </div>
                        <div id="errMsg1"></div>

                        <div class="modal-footer">
                            <button type="submit" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="submit" id="submit" class="btn btn-primary" data-toggle="modal" data-target="#myModal" >OK</button>
                        </div>