Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery event firing twice after .load()

I've come across an issue where jQuery events fire twice after $.load() is called. The event handler is placed in the load() callback function, and this seems to be the only place where events fire twice on the script.

I've tried adding event.stopPropogation() and event.preventDefault(), as these seem to be common suggestions with jQuery events firing more than one. I'm not sure if my code is bubbling improperly or what. Any feedback would be helpful.

Here's an extract of some of the code where you see the behavior.

$("div.questions").load("question_source.php #simplified_a", function(){

                ...

                // Line 1
                $("#some_id").change(function(){
                    cantBeNegative(this);
                    adjusted_gross_income = $(this).val();
                    console.log(adjusted_gross_income);
                    // event.stopPropagation();
                    // event.preventDefault();
                });

You can clearly see the event firing twice with the console.log bit I've got in there. Any advice would be appreciated!


EDIT

OK, I checked through everything on the live page based on some of the suggestions, and there's definitely only one <div id="questions"> in existence when the problem is occurring. So, it doesn't appear to be an HTML problem.

I also checked to see if the event was actually being called twice, and as far as I can tell, the event is only being called once.

Now, I added a .on() event attached to the document which is called on the dynamically created elements, and that only fires once. .on() is not called within the .load() callback. Here's an example used on one of the other input boxes on the page which works without any problems:

$(document).on('change', "#SWA_mothers_income", function(){
console.log("mothers income changes from on()");
});

So, that works properly, but when tested on the same input within the .load() callback function, it fires twice, regardless of how it's called. So, it seems to me that it's almost certainly an issue with .load(). I wouldn't exactly call myself an expert in this, so if someone can figure out the issue, I'd love to know the answer. As it stands, I'm going to rewrite this code using .on().


SECOND EDIT

Adding $("#some_id").unbind('change'); before the 'change(function()) bit did the trick!

like image 473
LoganEtherton Avatar asked Sep 03 '13 14:09

LoganEtherton


1 Answers

add this line

$("#some_id").unbind('change');

before

$("#some_id").change(function(){});

like image 55
Hager Aly Avatar answered Sep 18 '22 08:09

Hager Aly