问题
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