Can anyone write how to make the select/deselect
function on the button click in 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 try doing this in a couple of ways but none of them want to work.
Abstract: To Select or Deselect Checkboxes using jQuery, all you need to do is use the prop() method along with the change event to achieve the requirement in a couple of lines of code. Gmail has a nice option where you can select and deselect multiple checkboxes (Emails) using the 'Select All' checkbox.
prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status.
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
In order to select all the checkboxes of a page, we need to create a selectAll () function through which we can select all the checkboxes together. In this section, not only we will learn to select all checkboxes, but we will also create another function that will deselect all the checked checkboxes.
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>
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With