dimanche 18 mars 2018

Range slider - checkboxes.

In short, I have to create a code, which should try to fill up all checkboxes in between a given range. So if you check 3 and 6, the range between those numbers will become automatically checked (4 and 5).

But, the numbers inside the range (in this case 4 and 5) should be impossible to uncheck (the last for loop in the srcipt). However the 'edge' numbers should be possible to uncheck (3 and 6).

Here's where I hit the wall. When I uncheck the 'range' numbers 3 and 6, the in range numbers 4 and 5 should become 'edge' numbers then. However they stay disabled. Any idea how to make it functional?

I hope I made myself clear. Thank you guys.

Here's the code: https://jsfiddle.net/o0gskmoL/5/

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        window.onload = function() {
            var lastChecked = null;
            var el = document.getElementsByClassName("list-item-checkbox");
            for (var i=0; i<el.length; i++) {
                el[i].addEventListener("click", myFunction);
            }
            function myFunction() {
                if (!lastChecked) {
                    lastChecked = this;
                    return;
                }

                var from = [].indexOf.call(el, this);
                var to = [].indexOf.call(el, lastChecked);
                var start = Math.min(from, to);
                var end = Math.max(from, to) + 1;
                var arr = Array.prototype.slice.call(el);
                var slicedArr = arr.slice(start, end);
                for(var j = 0; j<slicedArr.length; j++){
                       slicedArr[j].checked = lastChecked.checked;
                };

                for(var k = start+2; k <= end-1; k++){
                    document.querySelector(`[value="${k}"]`).disabled = true;
                }

                lastChecked = this;


                console.log(lastChecked);
            }
        };
    </script>
</head>
<body>
    <ul>
        <li><label><input type="checkbox" class="list-item-checkbox" value="1">Checkbox 1</label></li>
        <li><label><input type="checkbox" class="list-item-checkbox" value="2">Checkbox 2</label></li>
        <li><label><input type="checkbox" class="list-item-checkbox" value="3">Checkbox 3</label></li>
        <li><label><input type="checkbox" class="list-item-checkbox" value="4">Checkbox 4</label></li>
        <li><label><input type="checkbox" class="list-item-checkbox" value="5">Checkbox 5</label></li>
        <li><label><input type="checkbox" class="list-item-checkbox" value="6">Checkbox 6</label></li>
        <li><label><input type="checkbox" class="list-item-checkbox" value="7">Checkbox 7</label></li>
    </ul>
</body>
</html>




Aucun commentaire:

Enregistrer un commentaire