I have a form with different fields inside. And I am using a dropdown button instead of normal select tag for better user experience. However, the problem is that this dropdown always gets focused when I press enter key on other text input fields. This is annoying and causing trouble.
<form>
<div class="row">
<div class="col-md-6">
<button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown">
<span class="dropdown-label">
Test
</span>
</button>
<button data-toggle="dropdown" class="btn btn-small btn-white dropdown-toggle">
<span class="caret"></span>
</button>
<ul class="dropdown-menu dropdown-select" role="menu">
<li><a>
Testing 1
</a></li>
<li><a>
Testing 2
</a></li>
</ul>
</div>
<div class="col-md-6">
<input type="text" class="form-control"/>
</div>
</div>
</form>
Here is the JS fiddle: http://jsfiddle.net/ergLb/
Do you guys have any idea why is that?
As all Twitter Bootstrap users know, the dropdown menu closes on click (even clicking inside it). To avoid this, I can easily attach a click event handler on the dropdown menu and simply add the famous event. stopPropagation() .
Just wrap the contents of the menu in a form tag. That's it.
By default, a dropdown menu is automatically positioned 100% from the top and along the left side of its parent. Add . dropdown-menu-right to a . dropdown-menu to right align the dropdown menu.
Solution : The dropdown should be toggled via data attributes or using javascript. In the above program, we have forgotten to add a data attribute so the dropdown is not working. So add data-bs-toggle="dropdown" to toggle the dropdown.
I have added type="button" and it works.
https://github.com/twbs/bootstrap/issues/3886
mdo gave the answer in a bootstrap issue ticket: https://github.com/twbs/bootstrap/issues/3886
You forgot type=button
at the button, which triggers the dropdown toggle. The code should read like this:
<button type="button" data-toggle="dropdown" class="btn btn-small btn-white dropdown-toggle">
<span class="caret"></span>
</button>
Seem like somehow by default when the enter
key was pressed inside the textbox, it'll trigger the click event on your dropdown. You can use e.preventDefault()
or return false
in order to prevent this default behavior:
$(".form-control").keydown(function(e){
if(e.keyCode == 13) {
return false;
}
});
Updated Fiddle
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