Search code examples
javascripttwitter-bootstrapdropdown

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?


Solution

  • 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