Reputation: 13
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.
Upvotes: 1
Views: 1942
Reputation: 1723
Get the element via attribute selector
for (let i=start; i<=end; i++){
document.querySelector(`[value="${i}"]`).disabled = true;
}
Here it is building the string in the selector with template literals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
And just setting the disabled attribute in the checkboxes via Javascript
document.querySelector('[value="7"]').disabled = true;
it will get an HTML like
<input type="checkbox" value="7" disabled>
https://www.w3schools.com/jsref/prop_checkbox_disabled.asp
Upvotes: 1
Reputation: 7330
It's impossible to make checkboxes uncheckable.
Sure, you can use
document.getElementById("elemnt-id").disabled = true;
or via
disabled
attribute in html
,
but there's always a way to uncheck them manually via Developer tools
. So you should have some validation on server too.
Upvotes: 2