Trigger change() event when setting <select>'s value with val() function

Goran Radulovic picture Goran Radulovic · Apr 23, 2011 · Viewed 232.5k times · Source

What is the easiest and best way to trigger change event when setting the value of select element.

I've expected that executing the following code

$('select#some').val(10);

or

$('select#some').attr('value',  10);

would result in triggering the change event, which i think is pretty logic thing to be done. Right?

Well, it isn't the case. You need to triger change() event by doing this

$('select#some').val(10).change();

or

$('select#some').val(10).trigger('change');

but i'm looking for some solution which would trigger change event as soon as select's value is changed by some javascript code.

Answer

criticman picture criticman · Sep 1, 2011

I had a very similar issue and I'm not quite sure what you're having a problem with, as your suggested code worked great for me. It immediately (a requirement of yours) triggers the following change code.

$('#selectField').change(function(){
    if($('#selectField').val() == 'N'){
        $('#secondaryInput').hide();
    } else {
        $('#secondaryInput').show();
}
});

Then I take the value from the database (this is used on a form for both new input and editing existing records), set it as the selected value, and add the piece I was missing to trigger the above code, ".change()".

$('#selectField').val(valueFromDatabase).change();

So that if the existing value from the database is 'N', it immediately hides the secondary input field in my form.