Here is a Boostrap navigation bar, containing a dropdown
menu, containing itself an <input>
.
When I click on the dropdown menu, it is succesfully displayed. The value of the <input>
is successfully changed to Bonjour
but this <input>
doesn't get the focus. Why ?
http://jsfiddle.net/rzsmdg4f/1/
How to give the focus to a input contained in a dropdown menu with .focus()
?
Code :
<div class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container">
<ul class="nav navbar-nav">
<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" id="maa">Dropdown<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu" style="min-width: 250px;">
<li>
<div style="padding:4px 20px;">Link:</div>
</li>
<li>
<div style="padding:4px 20px;">
<input class="form-control" id="ha" type="text" placeholder="blabla" />
</div>
</li>
</ul>
</li>
</ul>
</div>
</div>
JS :
{
var maa = document.getElementById('maa');
console.log(maa);
maa.addEventListener('click', function () {
console.log($('#ha'));
$('#ha').val('Bonjour');
$('#ha').focus();
});
};
For the dropdown, we add a transform to make it animate from the corner. Then we add an opacity of 0 to hide it. Now we need to target the hover. We use the #user-menu:focus and then target the following (~) dropdown.
The <select> autofocus attribute is a boolean attribute that specifies that the drop-down list should automatically get focus when the page loads.
jsFiddle Demo
The element exists at the time of the click, so changing its value and logging it will properly show the current state of the element. However, it has not been displayed yet and as a result focusing it will not really have any effect. You could probably refactor some small snippet in the library to expose a hook that you could use to make your focus work. Or, you could make the observation that in the very next event handler the element will be visible and use a small timeout.
maa.addEventListener('click', function () {
console.log($('#ha'));
$('#ha').val('Bonjour');
setTimeout(function(){$('#ha').focus();},10);//timeout here
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With