Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i call select box on change while changing select value using jquery?

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?

like image 950
Jayababu Avatar asked Apr 27 '15 07:04

Jayababu


1 Answers

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>
like image 199
Satpal Avatar answered Oct 31 '22 15:10

Satpal