I am having a select box like this
<select class="cars" onChange="carName()">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
If am changing dropdown values carName
function is calling and working as expected. If suppose I change the value using jQuery like this
$('.cars').val('Audi');
I want that carName()
function to be called.How can I do this?
You need to .trigger()
event programmatically
Execute all handlers and behaviors attached to the matched elements for the given event type.
Also, value is case sensitive, so use correct value. use audi
instead of Audi
Code,
$('.cars').val('audi').trigger('change');
Also since you are using jquery bind event using it like
$('.cars').on('change', carName); //Or, $('.cars').change(carName);
function carName() {
alert('In carName function');
}
$(document).ready(function() {
$('.cars').val('audi').trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="cars" onChange="carName()">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
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