简体   繁体   中英

Create array with checked boxes with javascript

i want to create a combination game checkin some elements with checkboxes

i need to create a array while the user check a checkbox and compare with the correct array

i dont know who do that

this is my inputs

<section class="draggable-items">
    <div class="check-tool">
        <input type="checkbox"  class="checkbox-tool" name="tool" id="SBD710" value="SBD710">
        <img class="draggable correct" draggable="true" src="img-game/WOOD/SBD710.png">
    </div>
    <div class="check-tool">
        <input type="checkbox" class="checkbox-tool" name="tool"  id="SCS220" value="SCS220">
        <img class="draggable correct" draggable="true" src="img-game/WOOD/SCS220.png">
    </div>
    <div class="check-tool">
        <input type="checkbox" class="checkbox-tool" name="tool"  id="SB201" value="SB201">
        <img  class="draggable correct" draggable="true" src="img-game/WOOD/SB201.png">
    </div>
    <div class="check-tool">
        <input type="checkbox" class="checkbox-tool" name="tool"  id="SB204" value="SB204">
        <img class="draggable correct" draggable="true" src="img-game/WOOD/SB204.png">
    </div>
    <div class="check-tool">
        <input type="checkbox" class="checkbox-tool" name="tool"  id=SBG700" value="SBG700">
        <img  class="draggable correct" draggable="true" src="img-game/WOOD/SBG700.png">
    </div>


</section>
    <button id="check" class="btn">Construye</button>

if somebody can explain me how to create that array with push method and who make the comparison with the correct combination array

Here's the demo for your solution

 let check = function () { let checkboxes = document.querySelectorAll("input[type=checkbox]"); let result = []; for (let i = 0; i < checkboxes.length; i++) { if (checkboxes[i].checked) { result.push(checkboxes[i].value); } else { result.push('null'); } } console.log(result); };
 <input type="checkbox" value="SBG701" onChange="check()" /> <input type="checkbox" value="SBG702" onChange="check()" /> <input type="checkbox" value="SBG703" onChange="check()" /> <input type="checkbox" value="SBG704" onChange="check()" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM