How to do Trigger('change') in a select input?

Asked

Viewed 433 times

2

I would like to simulate a change event in my input, but I’m not getting it to work.

As soon as the page loads I select a different value in my input that way:

$("#selExercicio option:contains('" + ano + "')").prop("selected", true);

Is working.

Next I try to do the Trigger:

$("#selExercicio").trigger("change");

My input change event is this:

$("#selExercicio").change(function () {
    debugger;
    alert('Mudou');
});

And it’s not calling Alert when loading the page, only when I change the value of the input by clicking the mouse.

Does anyone have any idea why it’s not working?

Fiddle

  • 1

    Can you make a jsfiddle reproducing the problem?

  • 2

    The code where you do the trigger is executed before or after the code where you assign the Handler?

  • The Trigger runs that I modify the selected value. What do you call Handler? I will try to make the fiddle.

  • I posted Fiddle http://jsfiddle.net/Skzp5/1/

  • @Joaopaulo Event Handler - the anonymous function you passed as a parameter to $(...).change. I see that, in fact, the problem was in the reverse order.

  • You can also use only $("#selExercicio").change(). Call the function change without passing parameter triggers the change event. This also applies to all other jQuery methods that handle events ;)

Show 1 more comment

1 answer

1


The mistake was that:

$("#selExercicio").trigger("change");

was being called before:

$("#selExercicio").change(function () {
    debugger;
    alert('Mudou');
});

Inverti and it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.