zerohero
zerohero

Reputation: 583

jQuery not triggering change event on dropdown

I'm trying to trigger the dropdown change event in jQuery (wordpress) but it's not working.

jQuery("select.buDropDown").each(function() { this.selectedIndex = 0 }).trigger('change');

Running this in console only changes the selectedIndex to 0, but never triggers the change event that shows/hides certain elements on the page.

However, running this in console, everything triggers fine:

$("select.buDropDown").each(function() { this.selectedIndex = 0 }).trigger('change');

I can't find any reasons why "$" would work but not "jQuery"

I tried wrapping it in:

jQuery(function($) {} 

to be able to use $ instead, but in the wordpress code it still doesn't trigger the change events

Any ideas?

Upvotes: 2

Views: 770

Answers (2)

zerohero
zerohero

Reputation: 583

Thank you for all contributions, you gave me some ideas I wanted to follow, and the following worked for my situation:

$("select.buDropDown").each(function() { 
        this.selectedIndex = 0;
     });
    $('select.buDropDown').parent().children('div').each(function() { $(this).hide(); });

Even though the dropdown's respective change events would have taken care of it, resetting to the original state is fine.

Upvotes: 0

Muhammad Qasim
Muhammad Qasim

Reputation: 1722

Your problem is that you are calling trigger function after closing the each loop. This would never happen. The following would work:

jQuery("select.buDropDown").each(function() { 
    this.selectedIndex = 0;
    jQuery(this).trigger('change'); 
});

And by the way, the following statement:

$("select.buDropDown").each(function() { this.selectedIndex = 0 }).trigger('change');

This means that select the collection of select.buDropDown and loop this collection and then trigger change on this collection. It will trigger change for only the first object in this collection. Not for the whole.

Upvotes: 1

Related Questions