Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change event being called twice

I have a form with some input and select boxes, each has class="myClass". I also have the following script:

$(document).ready(function() {
    $(".myClass").change(function() {
        alert('bla');
    })
});

I dont understand why after each change in select box or input box, this function is being called twice. What's wrong here?

Appreciate your help!

like image 922
Israel Avatar asked Mar 28 '11 20:03

Israel


6 Answers

All I can think of is that you used the same class on the form itself. if so, remove the myClass style from your form tag.

Corrected : http://jsfiddle.net/rY6Gq/1/

Faulty one with double alert: http://jsfiddle.net/rY6Gq/

like image 118
Marc Uberstein Avatar answered Nov 08 '22 07:11

Marc Uberstein


e.stopImmediatePropagation(); is what worked for me.

$(document).ready(function() {
    $(".myClass").change(function(e) {
        e.stopImmediatePropagation();
        alert('bla');
    })
});
like image 41
jwebb Avatar answered Nov 08 '22 06:11

jwebb


Its a bug, You'd add

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

before any change call

like image 12
diego matos - keke Avatar answered Nov 08 '22 05:11

diego matos - keke


It happens when the same class or whatever attribute you are binding also has the same name parent or child. Obviously, when you change a child, parent also gets changed (its child changes). If they have the same class or attribute, it should fire twice. For example, in the following if you bind to "myClass", it will be called twice.

<div class="myclass">
<select class="myClass">   </select>
</div>
like image 5
Selay Avatar answered Nov 08 '22 06:11

Selay


if this occurred in IE, it may be this bug as it was for me: http://bugs.jquery.com/ticket/6593

updating to jQuery 1.7.1 worked for me.

like image 3
user996015 Avatar answered Nov 08 '22 06:11

user996015


For me - I had written the on change event inside a function. Moving it to $(document).ready(function () {}); solved my case.

like image 1
jAntoni Avatar answered Nov 08 '22 07:11

jAntoni