Reputation: 49
I'm doing a project with contains a simple form that the user must fill and then a button to submit it. The first time you click on the button the event (called by .click()) happens correctly, but the second time the event happens twice, and so on.. if I have submit my form 100 times it would play the event 100 times.
function MenuOpinion(){
$("#registraropinion").click(IngresarOpinion);
}
function IngresarOpinion(){
var seleccionada= $("#perpelicula option:selected").html();
if(seleccionada=="Seleccione"){
$("#error_opinion").html("Seleccione una película de la lista");
}else{
$("#error_opinion").html("");
var nuevaOpinion=[];
nuevaOpinion['nombre']=$("#pernombre").val();
nuevaOpinion['edad']=$("#peredad").val();
nuevaOpinion['opinion']=$("#peropinion").val();
nuevaOpinion['puntaje']= parseInt($("#puntaje option:selected").html());
nuevaOpinion['aclaracion']=$("#txtaclaracion").val();
for(var i=0; i<listaPeliculas.length; i++){
if(listaPeliculas[i]['titulo']==seleccionada){
listaPeliculas[i]['opiniones'].push(nuevaOpinion);
}
}
/*Aviso al usuario y vuelvo al inicio*/
alert("Opinión guardada");
$("#opinion").hide();
$("#inicio").show();
}
}
I'm really can't find the problem. I leave the code that has to do with this button.
Upvotes: 0
Views: 1235
Reputation: 33661
Change
function MenuOpinion(){
$("#registraropinion").click(IngresarOpinion);
}
to
$(function(){ // <-- on document ready
$("#registraropinion").click(IngresarOpinion); // <-- bind the click event once on dom ready
}}
My guess is you are running MenuOpinion() on each submit - causing it to bind another click handler to your element - so 100th click will trigger all 100 click event handlers bound to your element
If you are using a form and a submit button then you should use
$(function(){ //<-- on document ready
$(yourform).submit(IngresarOpinion); // <-- bind the click event
}}
then have an e.preventDefault inside the function
function IngresarOpinion(e){
e.preventDefault();
// rest of your code
}
Upvotes: 1