Trigger change() event when setting <select>'s value with val() function
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.
One thing that I found out (the hard way), is that you should have
$('#selectField').change(function(){
// some content ...
});
defined BEFORE you are using
$('#selectField').val(10).trigger('change');
or
$('#selectField').val(10).change();
The straight answer is already in a duplicate question: Why does the jquery change event not trigger when I set the value of a select using val()?
As you probably know setting the value of the select doesn't trigger the change() event, if you're looking for an event that is fired when an element's value has been changed through JS there isn't one.
If you really want to do this I guess the only way is to write a function that checks the DOM on an interval and tracks changed values, but definitely don't do this unless you must (not sure why you ever would need to)
Added this solution:
Another possible solution would be to create your own .val()
wrapper function and have it trigger a custom event after setting the value through .val()
, then when you use your .val() wrapper to set the value of a <select>
it will trigger your custom event which you can trap and handle.
Be sure to return this
, so it is chainable in jQuery fashion