简体   繁体   中英

How can I open a dropdown <select> with focus jquery event?

I'm trying to open automatically a drop downdown menu when I hit the "Tab" key on the keyboard and focus my element.The focus function works, but the trigger doesn't. My intention is to force the "click" event so it opens up.

Here are my HTML examples. https://jsfiddle.net/jaelsvd/yqnoo5z9/ or also the snippet.

  $(".myTab").focus(function(){ $(".myTab").trigger("click"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="myTab"> <option> Example 1 </option> <option> Example 2 </option> <option> Example 3 </option> <option> Example 4 </option> <option> Example 5 </option> <option> Example 6 </option> <option> Example 7 </option> <option> Example 8 </option> <option> Example 9 </option> </select> <select class="myTab"> <option> 1 </option> <option> 2 </option> <option> 3 </option> <option> 4 </option> <option> 5 </option> <option> 6 </option> <option> 7 </option> <option> 8 </option> <option> 9 </option> </select> <select class="myTab" > <option> Jael </option> <option> Joe </option> <option> Andrea </option> <option> Toby </option> <option> Bob </option> <option> John </option> <option> Alan </option> <option> Mandy </option> <option> Melody </option> </select> 

click event does not open the drop down list

what you can do is change the size of the drop down list, so that it appears open

$(".myTab").focus(function(){

  $(".myTab").attr("size", 10);
});

you can later change the size to 1

You can also try the following :

$(".myTab").focus(function(){

    var length = $('.myTab option').length;
    //open dropdown
    $(this).attr('size', length);

   // to close
   $(this).attr('size', 0);
});

By doing this you will get the option length of exact size.

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