Using Dropstrap Dropdown - Entering Focus Through JQuery

I am using the following code, which is part of the Bootstrap Framework.

My goal is to focus the input by clicking on <a>name</a> using the Jquery click / focus function. I already know him about the data-toggle="dropdown" attribute in link a so that it doesn't work. I am not very experienced. Hope someone helped me!

 <html> <body> <li class="dropdown"> <a class="dropdown-toggle" id="dLabel" role="button" data-toggle="dropdown" data-target="#" href="#"><i class="icon-user"></i> name </a> <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel"> <li> <form ...> <input type="text" id="4711" /> </form> </li> </ul> </li> </body> </html> <script> $('#dLabel').click(function() { $('#4711').focus(); }); </script> 
+6
source share
3 answers

You should put your code in a document handler:

{for bootstrap, you can use the timeout as a simple workaround}

WATCH DEMO

 $(function () { $('#dLabel').click(function () { setTimeout(function(){$('#login').focus();},0); }); $('.dropdown input[type=text]').click(function(e){ e.stopPropagation(); }); }); 
+5
source

A workaround is to use the label element with the for attribute instead of the element.

 ... <li class="dropdown"> <label for="4711" class="dropdown-toggle" id="dLabel" role="button" data-toggle="dropdown"> <i class="icon-user"></i> name </a> <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel"> <li> <form ...> <input type="text" id="4711" /> </form> </li> </ul> </li> ... 
0
source

If you cannot use the label and want to use the link, you can monitor the events caused by the drop-down lists and process them in this way. You can see all the events at: https://getbootstrap.com/docs/4.0/components/dropdowns/#events

In this case, you would like to use the show.bs.dropdown event so that your code is like this:

 <html> <body> <li id="dropdownParent" class="dropdown"> <a class="dropdown-toggle" id="dLabel" role="button" data-toggle="dropdown" data-target="#" href="#"><i class="icon-user"></i> name </a> <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel"> <li> <form ...> <input type="text" id="4711" /> </form> </li> </ul> </li> </body> </html> <script> $('#dropdownParent').on('shown.bs.dropdown', function() { $('#4711').focus(); }); </script> 
0
source

Source: https://habr.com/ru/post/944889/


All Articles