简体   繁体   English

如何在已选择的选项上触发功能onchange

[英]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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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