简体   繁体   中英

Open Bootstrap dropdown when ENTER key is pressed in input

I want to open a Bootstrap dropdown when the ENTER key is pressed inside an input.

HTML:

<div class="top dropdown" id="search-bar">
  <span class="fa fa-search" id="search" data-toggle="dropdown"></span>                 

  <input type="text" id="search" class="form-control" placeholder="Search" data-toggle="dropdown"/> 

  <ul class="dropdown-menu"> 
    <li> Something </li>                   
  </ul> 
</div> <!--search bar -->

JS:

$('input#search').keypress(function(e) {
  if(e.keyCode == 13) {
    $('input#search').dropdown();
  }
});

The problem is that data-toggle="dropdown" triggers the dropdown when I just click inside the input. I only want to trigger it on ENTER.

I found couple issues with your code.

  • There is wrong id assignment, search is set as id for both span icon and for the input.

  • The dropdown is trigged on input click due to the assigned
    data-toggle=dropdown attribute to the input.

Based on the mentioned issues with your code try this instead:

    <div class="top dropdown" id="search-bar">
      <span class="fa fa-search" id="btn-search" data-toggle="dropdown"></span>

      <input type="text" id="search" class="form-control" autocomplete="off" placeholder="Search" />

      <ul class="dropdown-menu">
        <li> Something </li>
      </ul>
    </div>
    <!--search bar -->


      $('input#search').keypress(function(e) {
      if (e.keyCode == 13) {
        $('#btn-search').click();
      }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM