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

痴心易碎 提交于 2019-12-05 15:17:22

问题


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;
        }
      });
    }
  });

回答1:


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




回答2:


You could just put your onchanged code into a separate function and then call it after you change the value.



来源:https://stackoverflow.com/questions/5808180/how-to-select-jquery-drop-down-val-and-trigger-the-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!