简体   繁体   中英

How can I produce an alert if three out of nine checkboxes are checked?

I have nine checkboxes linked to nine images and three of them use the name 'correct' using the code shown below.

<div class="nine">
            <label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
            <input type="checkbox" class="chk" id="correct1" name="correct"/>
            </div>

The remaining six are unnamed using the code shown below.

<div class="nine">
            <label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
            <input type="checkbox" class="chk" id="incorrect4"/>
            </div>

I currently have the following code to produce an alert if the three checkboxes with the name "correct" are checked but it isn't working.

<script>
var i, correct = document.getElementsByName('correct');
            for (i = 0; i <= correct.length; i++) {
                if (correct[i].checked) {
                    alert('correct');
                    return true;
                }
            }
            alert('incorrect');
            return false;
            </script>

Can anyone help me with this?

Loop over all of the checkboxes, checking their state. Once this is done, create a variable "correct" and initialize it to true. Then go to each state in the variable and, if you find that its name isn't "correct" and it is checked or its name is "correct" and it isn't correct, set the variable to false. Then check if the variable is true and, if it is, display the alert.

View an example here: https://repl.it/GxsE/9

Using ES6:

 const correctInputs = [...document.querySelectorAll('input[name="correct"]')]; const alertIfThree = () => { const checkedCorrectInputs = correctInputs.filter(input => input.checked); if (checkedCorrectInputs.length > 2) { alert('Alert'); } }; correctInputs.forEach(input => input.addEventListener('click', alertIfThree)); 
 <input type="checkbox" name="correct"/> <input type="checkbox" name="correct"/> <input type="checkbox" name="correct"/> <input type="checkbox" name="correct"/> <input type="checkbox" name="correct"/> 

  • document.querySelectorAll('input[name="correct"]') gets all inputs with name "correct".
  • [...CODE] is spread operator , it converts code from previous point to array.
  • correctInputs.forEach(input => input.addEventListener('click', alertIfThree)) adds click event listener to each of them. That event listener is function alertIfThree() .
  • alertIfThree() filters out those input elements that are not checked and produces alert if there are more than 2 of them.

EDIT

In response to your comment:

 // jshint esnext: true const inputs = [...document.querySelectorAll('input[name="correct"], input[name="incorrect"]')]; const alertIfCorrect = () => { const checkedInputs = inputs.filter(input => input.checked), noIncorrectCheckedInputs = checkedInputs.find(input => input.name === 'incorrect') === undefined; if (checkedInputs.length > 2 && noIncorrectCheckedInputs) { alert('Alert'); } }; inputs.forEach(input => input.addEventListener('click', alertIfCorrect)); 
 <p>Correct: <input type="checkbox" name="correct"/> <input type="checkbox" name="correct"/> <input type="checkbox" name="correct"/> <input type="checkbox" name="correct"/> <input type="checkbox" name="correct"/> </p> <p>Incorrect: <input type="checkbox" name="incorrect"/> <input type="checkbox" name="incorrect"/> <input type="checkbox" name="incorrect"/> </p> 

  • const is ES6 constant . "The value of a constant cannot change through re-assignment, and it can't be redeclared" .
  • [...CODE_HERE] is so called spread syntax . Here, it turns what it contains after ellipsis into an array. Other way to do it would be to use Array.from() .
  • () => { and input => CODE_HERE are arrow functions . They are ES6's syntactic sugar for function declaration.

    What stands before => are parameters. () stands for 0 parameters. If you wanted function that takes few parameters, those braces would need to have those few parameters inside them. For one parameter, parameter's name can replace braces altogether (like in second code in this bullet point).

    What stands after => is either expression or group of statements. Statements are surrounded by curly brackets ( {} ). If you omit them, you are writing an expression that your function will return. For example input => input.checked is equivalent to function(input) { return input.checked; } function(input) { return input.checked; } .
  • filter() and find() are methods of array prototype. They respectively filter and search an array using condition defined in a function that is passed to them as a parameter. Read more by following those two links.

If you need something else explained, let me know. Those functions and structures here are pretty... fresh, so you can just not know them yet.

I put this in a JSfiddle and it works for me. I just wrapped your JS in a function and added an onclick event.

  <div class="nine">
            <label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
            <input type="checkbox" class="chk" id="correct1" name="correct"onclick="validate()"/>
</div>


<div class="nine">
            <label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
            <input type="checkbox" class="chk" id="incorrect4" onclick="validate()"/>
 </div>


    <script type=text/javascript">
    function validate()
    {
    var i, correct = document.getElementsByName('correct');
                for (i = 0; i <= correct.length; i++) {
                    if (correct[i].checked) {
                        alert('correct');
                        return true;
                    }
                }
                alert('incorrect');
                return false;
    }

    </script>

Check the loop. Use for (i = 0; i < correct.length; i++) { instead for (i = 0; i <= correct.length; i++) {

 var i, correct = document.getElementsByName('correct'); var correct_answers = []; function validate(){ correct_answers = []; for (i = 0; i < correct.length; i++) { var element = correct[i].getAttribute("id"); var checked = correct[i].checked; correct_answers.push({element,checked}); } } function show(){ document.getElementById('results').innerHTML =""; for(var e=0;e<correct_answers.length;e++){ var box = document.createElement('div'); box.innerHTML = correct_answers[e].element+ " " + correct_answers[e].checked+ "<br>"; document.getElementById('results').appendChild(box); } } 
 <div class="nine"> <label for="correct1"><img class="picture1" src="picture1.jpg"/></label> <input type="checkbox" onclick="validate()" class="chk" id="correct1" name="correct"/> </div> <div class="nine"> <label for="correct2"><img class="picture1" src="picture1.jpg"/></label> <input type="checkbox" onclick="validate()" class="chk" id="correct2" name="correct"/> </div> <div class="nine"> <label for="correct3"><img class="picture1" src="picture1.jpg"/></label> <input type="checkbox" onclick="validate()" class="chk" id="correct3" name="correct"/> </div> <div class="nine"> <label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label> <input type="checkbox" onclick="validate()" class="chk" id="incorrect4"/> </div> <div class="nine"> <label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label> <input type="checkbox" onclick="validate()" class="chk" id="incorrect5"/> </div> <div class="nine"> <label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label> <input type="checkbox" onclick="validate()" class="chk" id="incorrect6"/> </div> <div class="nine"> <label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label> <input type="checkbox" onclick="validate()" class="chk" id="incorrect7"/> </div> <div class="nine"> <label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label> <input type="checkbox" onclick="validate()" class="chk" id="incorrect8"/> </div> <button onclick="show();">show results</button> <div id="results"></div> 

It will require some javascript. You will need o check the checkboxes each time one changes. So to start with you will need to check your checkboxes, assuming they have an assigned class of 'chk'. This can be done with a querySelector.

Each time a checkbox changes, the function 'check_checkboxes()' is called. This function will see for each checkbox with name='correct' if it is checked and then increment 'count'

 var checkboxes = document.querySelectorAll(".chk"); var correct = document.querySelectorAll("[name=correct]"); function check_checkbox() { var count = 0; [].forEach.call(correct, function(item) { if (item.checked) { count++; } }); if (count >= 3) { alert("count of 3 or more"); } } [].forEach.call(checkboxes, function(item) { item.addEventListener("change", function() { check_checkbox(); }, false); }); 
 <div class="nine"> <label for="correct1"><img class="picture1" src="http://placehold.it/40x40"/></label> <input type="checkbox" class="chk" id="correct1" name="correct" /> </div> <div class="nine"> <label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label> <input type="checkbox" class="chk" id="incorrect4" /> </div> <div class="nine"> <label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label> <input type="checkbox" class="chk" id="incorrect4" name="correct" /> </div> <div class="nine"> <label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label> <input type="checkbox" class="chk" id="incorrect4" /> </div> <div class="nine"> <label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label> <input type="checkbox" class="chk" id="incorrect4" name="correct" /> </div> 

在代码中使用document.querySelectorAll('input [name] = correct')。

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