Javascript Click Events Firing Multiple Times?
Solution 1:
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">
<inputid="male"type="radio"name="gender"value="male"><labelclass="left-m"for="male"><span></span> Male </label></div><divclass="right-item"><inputid="female"type="radio"name="gender"value="female"><labelfor="female"><span></span> Female </label></div>
Then in your JavaScript, just call getData.init();
getData.init();
Solution 2:
bind a single click event, if you are calling this multiple time then first remove the click event and the append it once again or use one()
try the following:
var s,
getData = {
settings: {
gender: "input[name='gender']",
age: "input[name='age']"
},
init: function() {
s = this.settings;
this.getInput();
},
getInput: function() {
$(s.gender+','+s.age).on("click", function() {
console.log($(this).val());
});
},
};
remove the click event and initiate the call at document ready
see demo: https://jsfiddle.net/qzrfwc3g/
or do it the normal way 3 lines of code:
$("input[name='gender'],input[name='age']").on("click", function() {
console.log($(this).val());
});
Solution 3:
I don't know why you want do it like this , as you code , I think there is a error here .
for (i in s) {
s[i].on("click", function() {
s[i].off();
console.log(this.getAttribute('value'))
});
}
You declare i
as global , when event fires , i
refers the same value .You can try this :
for (let i in s) {
s[i].on("click", function() {
s[i].off();
console.log(this.getAttribute('value'))
});
}
Solution 4:
you are adding multiple click events to same element that why you get multiple console.log for one click. To resolve this just add a condition before assigning event listners.
var s,
getData = {
cacheDOM: {
gender: $("input[name='gender']"),
age: $("input[name='age']")
},
init: function() {
if(!s){
s = this.cacheDOM;
this.getInput();
}
},
getInput: function() {
for (i in s) {
s[i].on("click", function() {
s[i].off();
console.log(this.getAttribute('value'))
});
}
},
};
Post a Comment for "Javascript Click Events Firing Multiple Times?"