cant use javascript to run html radio button - javascript

I have this script in my < head > :
<script>
var rad = document.getElementsByName('search_type');
alert(rad[1]);
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
(prev)? console.log(prev.value):null;
if(this !== prev) {
prev = this;
}
console.log(this.value)
alert(this.value);
};
}
</script>
and this is my form:
<form name="search_form" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr>
<td class="input">
<input type="radio" name="search_type" value="search_code" checked>1st type<br>
<input type="radio" name="search_type" value="search_title">2nd type<br>
<input type="radio" name="search_type" value="search_filter">3rd type<br>
</td>
<tr/>
</table>
</form>
but none of alerts work. I have no error in console. please help.

You are running the script before the HTML code for the radio buttons has been parsed.
Place the script below the form, or run the code in the load event:
window.onload = function() {
var rad = document.getElementsByName('search_type');
alert(rad[1]);
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
(prev)? console.log(prev.value):null;
if(this !== prev) {
prev = this;
}
console.log(this.value)
alert(this.value);
};
}
};

You could simplify your code with some jQuery:
$(document).ready(function() {
var rad = $('[name="search_type"]');
console.log(rad);
var prev = null;
rad.click(function() {
console.log(prev, $(this).is(':checked'));
if (this !== prev) {
prev = this;
}
console.log(prev, $(this).is(':checked'));
});
});
http://jsfiddle.net/f2aDK/

Move it script after form.
Until Browser parse DOM element, javascript cannot read DOM.
<form name="search_form" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr>
<td class="input">
<input type="radio" name="search_type" value="search_code" checked>1st type<br>
<input type="radio" name="search_type" value="search_title">2nd type<br>
<input type="radio" name="search_type" value="search_filter">3rd type<br>
</td>
<tr/>
</table>
</form>
<script>
var rad = document.getElementsByName('search_type');
alert(rad[1]);
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
(prev)? console.log(prev.value):null;
if(this !== prev) {
prev = this;
}
console.log(this.value)
alert(this.value);
};
}
</script>

first add jquery lib
$(document).ready(function () {
$('[name="search_type"]').live('click', function (event) {
var rad = document.getElementsByName('search_type');
alert(rad[1]);
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
(prev)? console.log(prev.value):null;
if(this !== prev) {
prev = this;
}
console.log(this.value)
alert(this.value);
};
}
});
});

Related

Get the form data on load submit

I want the form data that was submitted on page load via POST method
Here is my code
<body onload="document.forms["Form1"].submit()">
<form id="Form1" method="POST" action="page2.aspx">
<input type="hidden" name="Status" value="success">
<input type="hidden" name="Date" value="05/05/2016">
</form>
</body>
What I want is to get the form data when ever this page is loaded
What I tried
document.getElementsByTagName('form')[0].onsubmit = function () {
var status, date;var str = '';
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.toLowerCase() === 'status') {
status= inputs[i];
}
else if (inputs[i].name.toLowerCase() === 'date') {
date= inputs[i];
}
}//for close
if (status != null) {
str += status.value;
}
else if (date != null) {
str += date.value;
}
}//func close
Why are you submitting the form while user has not even filled the form body onload !
If you are allowed to use Jquery it will do your task easy
document.getElementsByTagName('form')[0].onsubmit = function () {
$(this).serializeArray();
}//func close
Please have a look at this link for details
Here is a small demonstration
$(document).ready(
function() {
$("#Form1").on('submit', function() {
var data = $(this).serializeArray()
console.log(data);
for (var i = 0; i < data.length; i++) {
document.body.innerHTML += 'Key: '+data[i].name +' and Value: '+ data[i].value + '</br>';
}
return false;
});
$("#Form1").submit();
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Form1" method="POST" action="page2.aspx">
<input type="hidden" name="Status" value="success">
<input type="hidden" name="Date" value="05/05/2016">
</form>
You need to write your code inside window.onload evnet.
Try this
window.onload = function() {
var str = '';
var status, date;
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.toLowerCase() === 'status') {
status= inputs[i];
}
else if (inputs[i].name.toLowerCase() === 'date') {
date= inputs[i];
}
}//for close
if (status != null) {
str += status.value;
}
if (date != null) {
str += date.value;
}
alert(str);
};
<<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<body onload="document.forms["Form1"].submit()">
<form id="Form1" method="POST" action="page2.aspx">
<input type="hidden" name="Status" value="success">
<input type="hidden" name="Date" value="05/05/2016">
</form>
</body>

Dynamic textbox creation based on textbox input

If I give semicolon as input means I have to create a textbox in jQuery. I tried this code and it flows correctly but it didn't show me the result.
$(document).ready(function (){
$("#hellotxt").on('keyup', function (event){
if (event.keyCode == 59)
{
var txt = $("#hellotxt").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
for (var i = 0; i < valueSortArray.length - 1; i++) {
alert("friends");
addbox();
}
}
});
});
addbox code is here
function addbox() {
var table = $(this).closest('table');
if (table.find('input:text').length >= 0) {
table.append('<tr> <input type="text" id="current Name" value="" /></td> <td><input type="text" id="current Name" value="" /> </td></tr>');
}
}
My ASp.Net Markup is
<asp:TextBox ID="hellotxt" runat="server" placeholder="hi;ji;ki;li;"> </asp:TextBox>
<table border="0" cellspacing="2">
<tr>
<td>
<input type="button" id="add" value="Add" />
<input type="button" id="del" value="Del" />
</td>
</tr>
you will get answer from this code..please you all guys check it out
$(document).ready(function (){
//page load
$("#hellotxt").on('keypress', function (event) {
console.log(event.which)
if (event.which == 59 || event.which == 186) {
var txt = $("#hellotxt").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
for (var i = 0; i < valueSortArray.length - 1; i++) {
addbox.call(this, valueSortArray);
}
}
});
function addbox(valueSortArray) {
var table = $(this).next('table').find("tbody");
table.find(".dyn").remove()
$.each(valueSortArray, function (i, v) {
console.log(i,v)
if (v)
table.append('<tr class="dyn"><td><input type="text" value="' + v + '" /></td></tr> ');
})
check below code keycode for ';' is 186 . check working example on fiddle
$("#hellotxt").on('keyup', function (event){
if (event.keyCode == 186)
{
var OBJ = $(this);
var txt = $("#hellotxt").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
for (var i = 0; i < valueSortArray.length - 1; i++) {
addbox(OBJ);
}
}
});
pass $(this)(hellotxt object) as argument in function
function addbox( OBJ ) {
var table = OBJ.next('table');
if (table.find('input').length >= 0) {
table.append('<tr> <input type="text" id="current Name" value="" /></td> <td><input type="text" id="current Name" value="" /> </td></tr>');
}
}

Multiple Checkbox validation at javascript

i have multiple checkbox, and all of it must be checked.
i write down the code but it doesnt work.
this is the code
html sample::
<form name="pembres" id="pembres" method="POST" onSubmit="return validateform()" style="margin:0;">
<input type="checkbox" name="lanjut[]" value="setuju2" />
<input type="checkbox" name="lanjut[]" value="setuju3" />
<input type="checkbox" name="lanjut[]" value="setuju4" />
<input type="checkbox" name="lanjut[]" value="setuju5" />
<input type="submit" value="Next Step" name="next" />
</form>
1st script at head tag
<script type="text/javascript">
function validateform(){
var success = false;
for (i = 0; i < document.pembres.elements['lanjut[]'].length; i++){
if (document.pembres.elements['lanjut[]'][i].checked){
success = true;
}
}
return success;
}
</script>
2nd script before /body
<script type="text/javascript">
var form = document.getElementById('pembres');
form.onsubmit = validateForm;
function validateForm() {
var isValid = false,
form = this,
els = form.elements['lanjut[]'];
i;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
return isValid;
}
</script>
You are setting isValid to true if any checkbox is checked, what you should do is return false if any checkbox is not checked.
function validateForm() {
var form = this,
els = form.elements['lanjut[]'], i;
for (i = 0; i < els.length; i += 1) {
if (!els[i].checked) {
return false;
}
}
return true;
}

Javascript: master checkbox to control all checkboxes in a table column

I have 5 checkboxes. One of them is the header for all checkboxes. If I check the header checkbox, all should check automatically, and if I uncheck it, all should uncheck. If I uncheck any of the child checkboxes, the header should automatically uncheck.
My code is like this:
<html>
<SCRIPT LANGUAGE="JavaScript">
function checkAll()
{
if(pp_checkall.checked==true)
{
for (i = 1; i <= pp_check.length; i++)
pp_check[i].checked = true ;
}
else
{
for (i = 1; i <= pp_check.length; i++)
pp_check[i].checked = false ;
}
}
</script>
<SCRIPT LANGUAGE="JavaScript">
function checkOne()
{
for (i = 1; i <= pp_check.length; i++)
{
if(pp_check[i].checked==false)
{
pp_checkall.checked = false ;
}
}
}
</script>
<body>
<table>
<tr><th width="1px"><input type="checkbox" text="Dharan" name="pp_checkall" onclick="checkAll();"></th></tr>
<tr>
</tr>
<tr> <input type="checkbox" name="pp_check" value="1" onclick="checkOne();"></tr>
<!--<tr> <input type="checkbox" name="pp_check" value="2" onclick="checkOne();"></tr>
<tr> <input type="checkbox" name="pp_check" value="3" onclick="checkOne();"></tr>
<tr> <input type="checkbox" name="pp_check" value="4" onclick="checkOne();"></tr> -->
</table>
</body>
</html>
Its working fine too, but in some cases only one <td> checkbox will appear, which stops the code from working. Please give some solution to solve this.
Try this
<script type="text/javascript" language="javascript">
var pp_check = document.getElementsByName('pp_check');
var pp_checkall = document.getElementsByName('pp_checkall')[0];
function checkAll() {
if (pp_checkall.checked == true) {
for (i = 0; i < pp_check.length; i++)
pp_check[i].checked = true;
}
else {
for (i = 0; i < pp_check.length; i++)
pp_check[i].checked = false;
}
}
function checkOne() {
var pp_check = document.getElementsByName('pp_check');
for (i = 0; i < pp_check.length; i++) {
if (pp_check[i].checked == false)
pp_checkall.checked = false;
}
}
</script>
You can use jQuery for the same.
$('input[name="pp_checkall"]').change(function () {
$('input[name=pp_check]').attr('checked', this.checked);
});
$('input[name="pp_check"]').change(function () {
$('input[name="pp_checkall"]').prop(
'checked',
$('input[name=pp_check]:not(:checked)').length === 0 ? true : false
);
});
Demo: http://jsfiddle.net/gPeh8/1/

How can I shift-select multiple checkboxes like GMail?

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?
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
It seems like every answer I can find online is completely dependent on jQuery for this. JQuery adds very little functionality. Here's a quick version that doesn't require any frameworks:
function allow_group_select_checkboxes(checkbox_wrapper_id){
var lastChecked = null;
var checkboxes = document.querySelectorAll('#'+checkbox_wrapper_id+' input[type="checkbox"]');
//I'm attaching an index attribute because it's easy, but you could do this other ways...
for (var i=0;i<checkboxes.length;i++){
checkboxes[i].setAttribute('data-index',i);
}
for (var i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener("click",function(e){
if(lastChecked && e.shiftKey) {
var i = parseInt(lastChecked.getAttribute('data-index'));
var j = parseInt(this.getAttribute('data-index'));
var check_or_uncheck = this.checked;
var low = i; var high=j;
if (i>j){
var low = j; var high=i;
}
for(var c=0;c<checkboxes.length;c++){
if (low <= c && c <=high){
checkboxes[c].checked = check_or_uncheck;
}
}
}
lastChecked = this;
});
}
}
And then initialize it whenever you need it:
allow_group_select_checkboxes('[id of a wrapper that contains the checkboxes]')
Recently, I wrote a jQuery plugin that provide that feature and more.
After including the plugin you just need to initialize the context of checkboxes with the following code snippet:
$('#table4').checkboxes({ range: true });
Here is the link to the documentation, demo & download: http://rmariuzzo.github.io/checkboxes.js/
Well, the post is quite old but here is a solution I've just come across:
jQuery Field Plug-In
I took the jQuery version from #BC. and transformed it into an ES6 version, since the code is actually pretty elegantly solving the problem, in case anyone still stumbles across this...
function enableGroupSelection( selector ) {
let lastChecked = null;
const checkboxes = Array.from( document.querySelectorAll( selector ) );
checkboxes.forEach( checkbox => checkbox.addEventListener( 'click', event => {
if ( !lastChecked ) {
lastChecked = checkbox;
return;
}
if ( event.shiftKey ) {
const start = checkboxes.indexOf( checkbox );
const end = checkboxes.indexOf( lastChecked );
checkboxes
.slice( Math.min( start, end ), Math.max( start, end ) + 1 )
.forEach( checkbox => checkbox.checked = lastChecked.checked );
}
lastChecked = checkbox;
} ) );
}
Got this solution from http://abcoder.com/javascript/jquery/simple-check-uncheck-all-jquery-function/ (now dead):
JavaScript and HTML code
var NUM_BOXES = 10;
// last checkbox the user clicked
var last = -1;
function check(event) {
// in IE, the event object is a property of the window object
// in Mozilla, event object is passed to event handlers as a parameter
if (!event) { event = window.event }
var num = parseInt(/box\[(\d+)\]/.exec(this.name)[1]);
if (event.shiftKey && last != -1) {
var di = num > last ? 1 : -1;
for (var i = last; i != num; i += di) {
document.forms.boxes['box[' + i + ']'].checked = true;
}
}
last = num;
}
function init() {
for (var i = 0; i < NUM_BOXES; i++) {
document.forms.boxes['box[' + i + ']'].onclick = check;
}
}
<body onload="init()">
<form name="boxes">
<input name="box[0]" type="checkbox">
<input name="box[1]" type="checkbox">
<input name="box[2]" type="checkbox">
<input name="box[3]" type="checkbox">
<input name="box[4]" type="checkbox">
<input name="box[5]" type="checkbox">
<input name="box[6]" type="checkbox">
<input name="box[7]" type="checkbox">
<input name="box[8]" type="checkbox">
<input name="box[9]" type="checkbox">
</form>
</body>
Inspired by the fine answers provided, here's a plain JavaScript version using Array.prototype to coerce nodelists to use array functions, rather than for loops.
(function () { // encapsulating variables with IIFE
var lastcheck = null // no checkboxes clicked yet
// get desired checkboxes
var checkboxes = document.querySelectorAll('div.itemslist input[type=checkbox]')
// loop over checkboxes to add event listener
Array.prototype.forEach.call(checkboxes, function (cbx, idx) {
cbx.addEventListener('click', function (evt) {
// test for shift key, not first checkbox, and not same checkbox
if ( evt.shiftKey && null !== lastcheck && idx !== lastcheck ) {
// get range of checks between last-checkbox and shift-checkbox
// Math.min/max does our sorting for us
Array.prototype.slice.call(checkboxes, Math.min(lastcheck, idx), Math.max(lastcheck, idx))
// and loop over each
.forEach(function (ccbx) {
ccbx.checked = true
})
}
lastcheck = idx // set this checkbox as last-checked for later
})
})
}())
<div class="itemslist">
<input type="checkbox" name="one" value="1">
<input type="checkbox" name="two" value="2">
<input type="checkbox" name="three" value="3">
<input type="checkbox" name="four" value="4">
<input type="checkbox" name="five" value="5">
</div>
I realy liked gyo's example and added some code so it works on all checkboxes with the same name.
I also added a MutationObserver so events are also handled on newly added checkboxes.
$(document).ready(function() {
var previouslyClicked = {};
var rangeEventHandler = function(event) {
if (event.shiftKey && previouslyClicked[this.name] && this != previouslyClicked[this.name]) {
var $checkboxes = $('input[type=checkbox][name='+this.name+']').filter(':visible');
var start = $checkboxes.index( this );
var end = $checkboxes.index( previouslyClicked[this.name] );
// console.log('range', start, end, this, previouslyClicked[this.name]);
$checkboxes.slice(Math.min(start,end), Math.max(start,end)+ 1).prop('checked', previouslyClicked[this.name].checked);
} else {
previouslyClicked[this.name] = this;
}
};
if ("MutationObserver" in window) { // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/MutationObserver to refresh on new checkboxes
var mutationCallback = function(mutationList, observer) {
mutationList.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (node.nodeName == 'INPUT' && node.type == 'checkbox') {
$(node).on('click.selectRange', rangeEventHandler);
}
});
});
};
var observer = new MutationObserver(mutationCallback);
observer.observe(document, {
childList: true,
attributes: false, // since name is dynamically read
subtree: true
});
}
$('input[type=checkbox][name]').on('click.selectRange', rangeEventHandler);
});
<html>
<head>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
First:
<input type="checkbox" name="first">
<input type="checkbox" name="first">
<input type="checkbox" name="first">
<input type="checkbox" name="first">
<input type="checkbox" name="first">
</div>
<div>
Second:
<input type="checkbox" name="second">
<input type="checkbox" name="second">
<input type="checkbox" name="second">
<input type="checkbox" name="second">
<input type="checkbox" name="second">
</div>
</body>
</html>
Found the better solution it works for both select and deselects checkboxes.
Uses a core javascript & 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', e.target.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>
Here is also another implementation similar to Outlooks multiple selection..
<script type="text/javascript">
function inRange(x, range)
{
return (x >= range[0] && x <= range[1]);
}
$(document).ready(function() {
var $chkboxes = $('.chkbox');
var firstClick = 1;
var lastClick = null;
var range = [];
$chkboxes.click(function(e) {
if(!e.shiftKey && !e.ctrlKey) {
$('#index-' + firstClick).prop('checked', false);
firstClick = $chkboxes.index(this) + 1;
if (firstClick !== null && firstClick !== ($chkboxes.index(this)+1)) {
$('#index-' + firstClick).prop('checked', true);
}
} else if (e.shiftKey) {
lastClick = $chkboxes.index(this) + 1;
if ((firstClick < lastClick) && !inRange(lastClick, range)) {
for (i = firstClick; i < lastClick; i++) {
$('#index-' + i).prop('checked', true);
}
range = [firstClick, lastClick];
} else if ((firstClick > lastClick) && !inRange(lastClick, range)) {
for (i = lastClick; i < firstClick; i++) {
$('#index-' + i).prop('checked', true);
}
range = [lastClick, firstClick];
} else if ((firstClick < lastClick) && inRange(lastClick, range)) {
for (i = 1; i < 100; i++) {
$('#index-' + i).prop('checked', false);
}
for (i = firstClick; i < lastClick; i++) {
$('#index-' + i).prop('checked', true);
}
range = [firstClick, lastClick];
}else if ((firstClick > lastClick) && inRange(lastClick, range)) {
for (i = 1; i < 100; i++) {
$('#index-' + i).prop('checked', false);
}
for (i = lastClick; i < firstClick; i++) {
$('#index-' + i).prop('checked', true);
}
range = [lastClick, firstClick];
}
}
});
});
This is jquery solution that I wrote and use:
All checkboxes have same class named chksel
For faster individual selection a class will carry the order
named chksel_index
Also each checkbox has an attribute named rg that contain same
index
var chksel_last=-1;
$('.chksel').click(function(ev){
if(ev.shiftKey){var i=0;
if(chksel_last >=0){
if($(this).attr('rg') >= chksel_last){
for(i=chksel_last;i<=$(this).attr('rg');i++){$('.chksel_'+i).attr('checked','true')}}
if($(this).attr('rg') <= chksel_last){for(i=$(this).attr('rg');i<=chksel_last;i++){$('.chksel_'+i).attr('checked','true')}}
}
chksel_last=$(this).attr('rg');
}else{chksel_last=$(this).attr('rg');}
})
this solution works for me, also ajax based for DataTables
https://jsfiddle.net/6ouhv7bw/4/
<table id="dataTable">
<tbody>
<tr>
<td><input type="checkbox"></td>
</tr>
<tr>
<td><input type="checkbox"></td>
</tr>
<tr>
<td><input type="checkbox"></td>
</tr>
<tr>
<td><input type="checkbox"></td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function() {
var $chkboxes = $('#dataTable');
var $range = '#dataTable tbody';
var $first = false;
var $indexWrapp = 'tr';
var lastChecked = null;
var $checkboxes = 'input[type="checkbox"]';
$chkboxes.on('click',$checkboxes,function(e) {
if ($first===false) {
lastChecked = $(this).closest($indexWrapp).index();
lastCheckedInput = $(this).prop('checked');
$first=true;
return;
}
if (e.shiftKey) {
var start = lastChecked;
var end = $(this).closest($indexWrapp).index();
$( $range+' '+$indexWrapp).each(function() {
$currIndex=$(this).index();
if( $currIndex>=start && $currIndex<=end ){
$(this).find($checkboxes).prop('checked', lastCheckedInput);
}
})
}
lastCheckedInput = $(this).prop('checked');
lastChecked = $(this).closest($indexWrapp).index();
});
</script>
Here is the Elegant implementation. The idea is to store the first selected input to the lastChecked variable and when the user selects the input field with shiftKey we will run a loop and toggle the inBetween(boolean) and mark all the checkboxes with true value.
Inspired by Wesbos.
let checkboxes = document.querySelectorAll('.wrapper input[type="checkbox"]');
let lastChecked;
function logic(e) {
let inBetween = false;
if (e.shiftKey) {
checkboxes.forEach(checkbox => {
if (checkbox === this || checkbox === lastChecked) {
inBetween = !inBetween;
}
if (inBetween) checkbox.checked = true;
})
}
lastChecked = this;
}
checkboxes.forEach((checkbox, i) => checkbox.addEventListener('click', logic));
.wrapper {
display: flex;
flex-direction: column;
}
<div class="wrapper">
<input type="checkbox" name="one">
<input type="checkbox" name="two">
<input type="checkbox" name="three">
<input type="checkbox" name="four">
<input type="checkbox" name="five">
</div>

Categories