phuwin
phuwin

Reputation: 3270

Jquery set select option by .val() does not fire on('change', )

JS Fiddle

<select id="panel" >
    <option value=1>One</option>
    <option value=2>Two</option>
    <option value=3>Three</option>
</select> 
<button id="button">Click me</button> <br> 

$('#button').click(function(){
  $('#panel').val(3); 
}); 
$('#panel').on('change',function(){
  alert('Hi'); 
});


Does anybody know how to get those thing works?

Upvotes: 3

Views: 5073

Answers (3)

Arun
Arun

Reputation: 1185

In your case it won't trigger change event, it is assignment, you have to call change event like. Change as follows
You have to use like HTML:

<select class="panel" >
                                                                                   <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
                                                                                </select> 
<button id="button">Click me</button> <!--click will change the select. But it doesnt fire the on change function. -->

JQUERY:

$('#button').click(function(){
    $('.panel').val(3);
    $( ".panel" ).change();
});
 $( ".panel" ).change(function() {
  alert( "Handler for .change() called." );
});

Upvotes: 1

Alex Char
Alex Char

Reputation: 33228

Additional you can use .trigger():

Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

$('#button').click(function() {
  $('#panel').val(3).trigger("change");
});
$('#panel').on('change', function() {
  alert('Hi');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="panel">
  <option value=1>One</option>
  <option value=2>Two</option>
  <option value=3>Three</option>
</select>
<button id="button">Click me</button>
<!--click will change the select. But it doesnt fire the on change function. -->

Upvotes: 7

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

You need to fire the event manually,

$('#panel').val(3).change();

Fiddle

Upvotes: 2

Related Questions