Daniel Contreras Daniel Contreras - 2 months ago 17
Javascript Question

Javascript click events firing multiple times?

Why is my function running multiple times?

var s,
getData = {

settings: {
gender: $("input[name='gender']"),
age: $("input[name='age']")
},

init: function() {
s = this.settings;
this.getInput();
},

getInput: function() {
for (i in s) {
s[i].on("click", function() {
s[i].off();
console.log(this.getAttribute('value'))
});
}
},
};


What I find odd is that when I don't click the same input twice it only runs once. For instance if I click 'male' and then 'female' it would show in the console

(1) male
(2) female


which logically makes sense to me, if I clicked 'male' 5 times then I get

(14) male


and it just gets larger and larger.

EDIT:
JSFiddle If you open console you can see what happens

Answer

What's happening is that getInput is being called for each click event, meaning that the loop is running each time, registering the event again. So each time you click the radio button the loop will attach an event to the DOM element again. You should only register the event once: https://jsfiddle.net/2jbLdo9n/

Remove the onclick event on the input:

<div class="right-item">
  <input id="male" type="radio" name="gender" value="male">
  <label class="left-m" for="male"><span></span> Male </label>
</div>
<div class="right-item">
  <input id="female" type="radio" name="gender" value="female">
  <label for="female"><span></span> Female </label>
</div>

Then in your JavaScript, just call getData.init();

getData.init();
Comments