简体   繁体   中英

how to trigger function onchange on already selected option

I have a dropdown which i would like to trigger a function when something is selected.

<select id="myselect">
   <option>1</option>
   <option>2</option>
   <option>3</option>
</select>

$(document).on("change", "#myselect", function(event) {
alert("you selected something");
});

The problem I have is that the function is not triggered if i choose option that has already been selected. I do understand that this is because nothing has been changed but is there a way around this?

I have tried

  <select id="myselect" onmousedown="this.value='';" >

this was ok for the few options, but when i had many options when i needed to scroll down to select it would jump up and select the wrong option. Any help much appreciated.

Try

 <select id="myselect" onclick="alert('Something selected')">
   <option>1</option>
   <option>2</option>
   <option>3</option>
</select>

UPDATE

 $(document).on("change", ".myselect",function(){ var idSelect = $(this).attr("id"); /*get the id select change*/ $(".myselect").each(function(){ var idSelectOther = $(this).attr("id");/*get the id of another select*/ if(idSelect != idSelectOther){ /*if id selected != other select then check value*/ if($("#"+idSelect).val() == $("#"+idSelectOther).val()){ /* if val same so alert the user.*/ alert("you already select this value"); } } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="myselect" id="sel1"> <option val="1">1</option> <option val="2">2</option> <option val="3">3</option> </select> <select class="myselect" id="sel2"> <option val="1">1</option> <option val="2">2</option> <option val="3">3</option> </select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM