ILya
ILya

Reputation: 121

Prevent dropdown close on keydown

Html:

<input id="input-smth`enter code here`" type="text" name="region" placeholder="Region" />

<ul class="nav">   <!-- "KB Menu"   -->
    <li class="dropdown kb_menu hideit">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown">Knowledge Bases<b class="caret"></b></a>
      <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel" id="kb_menu">
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ul>
    </li>
</ul>

Javascript:

$('#input-smth').on('keydown', function( event ){
    $('#kb_menu').dropdown('toggle');
    event.stopPropagation();

});

When typing dropdown opens, but then on the second type, it closes. How to prevent toggling and keep dropdown opened, when I continue typing?

Upvotes: 2

Views: 1120

Answers (2)

Hevar
Hevar

Reputation: 1529

Since you use toggle it will do just that, toggle (show/hide) for each keydown.

You can use the keydown to display and add a button to close it or hide it when its off focus.

Shows on keydown hides when focusout:

$('#input-smth').on('keydown', function( event ){
  $('#kb_menu').show();
  event.stopPropagation();
});

$("#input-smth").focusout(function() {
  $('#kb_menu').hide();
});

Also JsFiddle

Upvotes: 3

a.barbieri
a.barbieri

Reputation: 2596

If you change toggle to open?

$('#kb_menu').dropdown('open');

I'm just guessing open can be a solution as I don't know which dropdown plugin you are using.


Otherwise a simple controller should do the trick:

var isOpen = false;
$('#input-smth').on('keydown', function( event ){
    // If is open don't go any further
    if ( isOpen ) { return }
    // Otherwise toggle the menu
    $('#kb_menu').dropdown('toggle');
    event.stopPropagation();
    isOpen = true
});

Upvotes: 0

Related Questions