0

I have following function to select/Deselect all checkbox.

$(function () {
        $("#selectall").click(function () {           
            $('.Employee').attr('checked', this.checked);
        });
        $(".Employee").click(function () {
            if ($(".Employee").length == $(".Employee:checked").length) {
                $("#selectall").attr("checked", "checked");
            } else {
                $("#selectall").removeAttr("checked");
            }

        });
    });

Its working properly but i am able to select/deselect all for first time on page load, for second time i need to reload the page.Means its not giving multiple time select/deselect functionality.

Huangism
  • 16,278
  • 7
  • 48
  • 74
  • 1
    Can you setup a Fiddle here? http://www.jsfiddle.net? – Newtt Sep 29 '14 at 14:37
  • What's your ([MCVE](http://stackoverflow.com/help/mcve/)) HTML? – David Thomas Sep 29 '14 at 14:39
  • please give us your HTML structure also . Would be a much help !! – Tushar Raj Sep 29 '14 at 14:40
  • You should then make a function for refreshing? Look at this page for your .attr(); wich is the problem. if ( $( elem ).is( ":checked" ) http://api.jquery.com/attr/ – NVRM Sep 29 '14 at 14:50
  • You need to use `.change()` jquery function as answered on this page: http://stackoverflow.com/questions/9180087/how-to-handle-change-of-checkbox-using-jquery – mk117 Sep 29 '14 at 14:57

1 Answers1

0

First problem is that you need to work off of the .prop() method. This reads the javascript checked property. Using the HTML checked attribute works for the first instance but fails for the rest. Next, you need to modify your logic just a little. I've included an example. Observe the javascript functions. Lastly, you should be using the change method or preferably the .on('change', function(){ ... }), but I'll keep my example closer to your original post.

$(function () {
        $("#selectall").change(function () {
            $('.Employee').prop('checked', this.checked);
        });
        $(".Employee").change(function () {
            if ($(".Employee").length == $(".Employee:checked").length) {
                $('#selectall').prop('checked', this.checked);
            } else {
                $('#selectall').prop('checked', false);
            }
        });
    });
label {
  display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label>test 1: <input type="checkbox" class="Employee"></label>
  <label>test 2: <input type="checkbox" class="Employee"></label>
  <label>test 3: <input type="checkbox" class="Employee"></label>
  <label>test 4: <input type="checkbox" class="Employee"></label>
  <label>test 5: <input type="checkbox" class="Employee"></label>
</div>

<label>Select All: <input id="selectall" type="checkbox"></label>
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129