In GMail, the user can click on one checkbox in the email list, hold down the Shift key, and select a second checkbox. The JavaScript will then select/unselect the checkboxes that are between the two checboxes.
I am curious as to how this is done? Is this JQuery or some basic (or complex) JavaScript?
Checkboxes allow a user to select multiple choices. Set the Name of each checkbox so you can identify them in the form submission data.
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.
The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.
I wrote a self-contained demo that uses jquery:
$(document).ready(function() { var $chkboxes = $('.chkbox'); var lastChecked = null; $chkboxes.click(function(e) { if (!lastChecked) { lastChecked = this; return; } if (e.shiftKey) { var start = $chkboxes.index(this); var end = $chkboxes.index(lastChecked); $chkboxes.slice(Math.min(start,end), Math.max(start,end)+ 1).prop('checked', lastChecked.checked); } lastChecked = this; }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> </head> <body> <input type="checkbox" id="id_chk1" class="chkbox" value="1" />Check 1<br/> <input type="checkbox" id="id_chk2" class="chkbox" value="2" />Check 2<br/> <input type="checkbox" id="id_chk3" class="chkbox" value="3" />Check 3<br/> <input type="checkbox" id="id_chk4" class="chkbox" value="4" />Check 4<br/> <input type="checkbox" id="id_chk5" class="chkbox" value="5" />Check 5<br/> <input type="checkbox" id="id_chk6" class="chkbox" value="6" />Check 6<br/> <input type="checkbox" id="id_chk7" class="chkbox" value="7" />Check 7<br/> </body> </html>
This is done through fairly simple javascript.
They keep track of the id of the last checked box and when when another checkbox is checked they use the shiftKey event attribute to see if shift was held while clicking the checkbox. If so they set the checked property of each checkbox in between the two to true.
To determine when a box is checked they probably use an onclick event on the checkboxes
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