lundi 27 août 2018

Strange onclick behavior for checkboxes. Trying to write onto browser console when a checkbox item is selected

Basically if I click on a checkbox, I want the name of the checkbox to be displayed on the console.

Here is the relevant javascript function and HTML.

javascript:

var list = [];

function test(){
      var checkBoxes = document.querySelectorAll('input[type=checkbox]')
    for(var i = 0; i < checkBoxes.length; i++) {
      checkBoxes[i].addEventListener('change',function(){
        if(this.checked){
          console.log(this.value)
          }
      });
  }
}

HTML:

<label><input type = "checkbox" onclick= "test()" name ="one" value ="one">test<br></label>
<label><input type = "checkbox" onclick= "test()" name ="two" value ="two" > test 1<br></label>
<label><input type = "checkbox" onclick= "test()" name ="three" value ="three" >test 2<br></label>
<label><input type = "checkbox" onclick= "test()" name ="four" value ="four" >test 3<br></label>
<label><input type = "checkbox" onclick= "test()" name ="five" value ="five" >test 4<br></label>
<label><input type = "checkbox" onclick= "test()" name ="six" value ="six" >Test 5<br></label>

If I click on the checkbox it is supposed to show in the console the name of the checked box.

However, something really strange happens and I don’t understand why it is. I have a vague inkling as to why it's happening but it's not quite clear.

When I click on the first check box for example. I click on the checkbox named "one". The console displays:
one (as required)

But if I click on the next check box (for example I clicked on the checkbox named "four"). In the console it displays:
four
four

And the next checkbox clicked (if it's the one named "five") The console shows:
five
five
five

and so on....(incrementally repeating the checkbox name displayed on the console each time I click on another checkbox)

Why is it repeating ? When I click on the checkbox there should be technically one onclick event. How come it's counting all the other ones and repeating the console.log(this.value) bit?

Thanks in advance for any who may be able to give some idea as to why this is happening.




Aucun commentaire:

Enregistrer un commentaire