Trigger change event <select> using jquery
is there anyway i could trigger a change event on select box on page load and select a particular option.
Also the function executed by adding the trigger after binding the function to the event.
I was trying to output something like this
<select class="check">
<option value="one">one</option>
<option value="two">two</option>
</select>
$(function(){
$('.check').trigger('change'); //This event will fire the change event.
$('.check').change(function(){
var data= $(this).val();
alert(data);
});
});
http://jsfiddle.net/v7QWd/1/
Solution 1:
Use val()
to change to the value (not the text) and trigger()
to manually fire the event.
The change event handler must be declared before the trigger.
Here's a sample
$('.check').change(function(){
var data= $(this).val();
alert(data);
});
$('.check')
.val('two')
.trigger('change');
Solution 2:
To select an option, use .val('value-of-the-option')
on the select element. To trigger the change element, use .change()
or .trigger('change')
.
The problems in your code are the comma instead of the dot in $('.check'),trigger('change');
and the fact that you call it before binding the event handler.
Solution 3:
$('#edit_user_details').find('select').trigger('change');
It would change the select html tag drop-down item with id="edit_user_details"
.