The logic in the change()
event handler is not being run when the value is set by val()
, but it does run when user selects a value with their mouse. Why is this?
<select id="single"> <option>Single</option> <option>Single2</option> </select> <script> $(function() { $(":input#single").change(function() { /* Logic here does not execute when val() is used */ }); }); $("#single").val("Single2"); </script>
When you dynamically set a value in a textfield using jQuery . val(), you have to manually trigger the . change event if you want to add extra code that trigger when the value of the field change.
The val() method is an inbuilt method in jQuery which is used to returns or set the value of attribute for the selected elements. This method apply on the HTML form elements. Syntax: There are three ways to use this method which are given below: $(selector).val()
$(document). ready(function(){ $('#countrylist'). change(function(e){ // Your event handler }); // And now fire change event when the DOM is ready $('#countrylist'). trigger('change'); });
Because the change
event requires an actual browser event initiated by the user instead of via javascript code.
Do this instead:
$("#single").val("Single2").trigger('change');
or
$("#single").val("Single2").change();
I believe you can manually trigger the change event with trigger()
:
$("#single").val("Single2").trigger('change');
Though why it doesn't fire automatically, I have no idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With