Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select jQuery drop down val() AND trigger the event?

I have a jQuery plugin registered on a drop down like this:

$('#country').linkToStates('#province');

I am manually selecting the drop down like this:

$('#country').val('United States');

But the onchange event is not triggering .linkToStates() which was registered before it. So it looks like val() only changes the drop down position but doesn't actually change the onchange event. Can anyone help?

BTW, this is the code of the registered if it helps:

  $.fn.extend({
        linkToStates: function(state_select_id) {
      $(this).change(function() {
        var country = $(this).attr('value');
        $(state_select_id).removeOption(/.*/);
        switch (country) {
          case 'Canada':
            $(state_select_id).addOption(canadian_provinces, false);
            break;
          case 'United States':
            $(state_select_id).addOption(us_states, false);
            break;
          default:
            $(state_select_id).addOption({ '' : 'Please select a Country'}, false);
            break;
        }
      });
    }
  });
like image 463
TruMan1 Avatar asked Apr 27 '11 17:04

TruMan1


1 Answers

Try this:

$('#country').val('United States').trigger('change');

or even

$('#country').val('United States').change();

You could read more about .trigger() here and .change() here

like image 150
Hari Pachuveetil Avatar answered Sep 18 '22 21:09

Hari Pachuveetil