简体   繁体   中英

there is only one option in a box, how do I get the value of option when I clicked on the option?

My option datas come from the database. That's why "select" may have one or more "option".When select has 2 option "change" event is working. it's ok. But when there is only one option change (also click and focus) event does not work. How do I get the value of option when I clicked on the option?

 $("#box").change(function(){ var selected=$("#box option:selected").val(); alert(selected); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="box"> <option value"1">1</option> <option value"2">2</option> </select> 

 $("#box").change(function(){ var selected=$("#box option:selected").val(); alert(selected); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="box"> <option value"1">1</option> </select> 

If you have one option then you can use click event of jquery instead of change event

 $(document).ready(function(){ if($("#box option").length>1){ $("#box").change(function(){ var selected=$("#box option:selected").val(); alert(selected); }); }else{ $("#box").click(function(){ var selected=$("#box option:selected").val(); alert(selected); }); } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="box"> <option value"1">1</option> <option value"2">2</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