Basically, I create a checkbox range with pure JS. What I can't figure out, how to make checked range impossible to uncheck. For example you check 2 and 5. So number 3 and 4 should be impossible to uncheck, but 2 and 5 is possible to uncheck.
<ul>
<li><input type="checkbox" value="1">One</input></li>
<li><input type="checkbox" value="2">Two</input></li>
<li><input type="checkbox" value="3">Three</input></li>
<li><input type="checkbox" value="4">Four</input></li>
<li><input type="checkbox" value="5">Five</input></li>
<li><input type="checkbox" value="6">Six</input></li>
<li><input type="checkbox" value="7">Seven</input></li>
</ul>
// JavaScript
var el = document.getElementsByTagName("input");
var lastChecked = null;
// Iterate through every 'input' element and add an event listener = click
for(var i = 0; i < el.length; i++){
el[i].addEventListener("click", myFunction);
}
function myFunction() {
// In this statement we check, which input is checked..✓
if (!lastChecked) {
lastChecked = this;
return;
}
// Declaring 'from' and 'to' and getting index number of an array-like inputs
var from = [].indexOf.call(el, this);
var to = [].indexOf.call(el, lastChecked);
/* Here we will know which 'check' will be the min and which will be the max with the
help of Math metods */
var start = Math.min(from, to);
var end = Math.max(from, to) + 1;
// Here we create an array from NodeList
var arr = Array.prototype.slice.call(el);
// Here we get a new array, where we declare the start and the end
// Start is the min, end is the max
var slicedArr = arr.slice(start, end);
// Now we iterate through every sliced input, and set its attribute to checked
for(var j = 0; j < slicedArr.length; j++){
slicedArr[j].checked = lastChecked.checked;
}
lastChecked = this;
}
Thank you for any help guys. It is my first post on stackoverflow by the way, so I'm verry sorry if I didn't post it correctly. Thank you.
Aucun commentaire:
Enregistrer un commentaire