Wahid Masud Wahid Masud - 5 months ago 16
Javascript Question

jquery .change() function not working on dynamically changed element

I have 1 button and 2 select elements. In my jquery code there are two event handlers:


  1. If I click the button then the 1st select box changes.

  2. If first select box is changed then the second box also changes.



So if I click the button then the 1st select box will change and as the 1st select box has changed so the second select box should be changed as well. But the second box is not changing. Here is my code. There is also a live link of my code.

<button id="b_a_1">
click to select 2nd element from A
</button>
<br><br><br>
A : <select id='s_a'>
<option value=1>1st element</option>
<option value=2>2nd element</option>
<option value=3>3rd element</option>
<option value=4>4th element</option>
</select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
B : <select id='s_b'>
<option value=1>First element is selected</option>
<option value=2>Second element is selected</option>
<option value=3>Third element is selected</option>
<option value=4>Fourth element is selected</option>
</select>
<script type="text/javascript">
$("#b_a_1").click(function(){
$("#s_a").val(2);
});

$("#s_a").change(function(){
$("#s_b").val($("#s_a").val());
});
</script>


I have also tried this :

$(document.body).on('change', '#s_a', function(){
$("#s_b").val($("#s_a").val());
});


But no good. How do I do it?

Answer

$("#b_a_1").click(function() {
  $("#s_a").val(2).change();//run the change event manually
});

$("#s_a").change(function() {
  $("#s_b").val($("#s_a").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b_a_1">
  click to select 2nd element from A
</button>
<br>
<br>
<br>A :
<select id='s_a'>
  <option value=1>1st element</option>
  <option value=2>2nd element</option>
  <option value=3>3rd element</option>
  <option value=4>4th element</option>
</select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; B :
<select id='s_b'>
  <option value=1>First element is selected</option>
  <option value=2>Second element is selected</option>
  <option value=3>Third element is selected</option>
  <option value=4>Fourth element is selected</option>
</select>

Use .change() to call change event manually