0

I want to call a function when already selected OPTION is select from drop-down.

$("#dropdown1").on("change",function(){
  alert($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdown1">
  <option value="one"> One </option>
  <option value="two"> Two </option>
  <option value="three"> Three </option>  
</select>

In above code, when i select option ONE than ALERT works. So, now option ONE is selected. But i want that when i select option ONE again, than function should call again.

  • You can think of `click` instead of `change`....as it not logically correct when ONE is already selected, you will select that again. – Mamun Feb 13 '19 at 10:18
  • It would be easier if you can store the earlier selected value to a variable and check if the newly selected value matches the existing value and if yes, then proceed with your alert. – Krishna Prashatt Feb 13 '19 at 10:20
  • 1
    Possible duplicate of [How to reselect already selected option](https://stackoverflow.com/questions/20234805/how-to-reselect-already-selected-option) – Sudhir Ojha Feb 13 '19 at 10:23
  • possible duplicate of https://stackoverflow.com/questions/647282/is-there-an-onselect-event-or-equivalent-for-html-select , where one can use `onclick` method to replicate the required behavior. – Mohit Pandey Feb 13 '19 at 10:25
  • @SudhirOjha Thanks man. found solution from there. [Solution](http://jsfiddle.net/mark_s/fef7j/1/) – kashyap chandarana Feb 13 '19 at 10:36

1 Answers1

1

Your event is change, if you select the same value again then there is no change, so no alert is fired.Introduce a dummy option which is hidden. Make all the calculations/manipulation you want to do with the selected value and then change the value to the dummy option element

$("#dropdown1").on("change",function(){
  alert($(this).val());
  $(this).val("");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdown1">
 <option value="" disabled  style="display:none;">Select</option>
  <option value="one" selected> One </option>
  <option value="two"> Two </option>
  <option value="three"> Three </option>  
</select>
ellipsis
  • 12,049
  • 2
  • 17
  • 33