2016-11-19 2 views
1

У меня есть рабочий раскрывающийся список, который отображается по щелчку текстового поля, но он всегда должен показывать на клавиатуре. У меня есть функция keyup, но вам все равно нужно щелкнуть после ввода, чтобы вызвать раскрывающееся меню.Bootstrap dropdown on keyup

 //This calls the delay function and will result in the customerNameUL_Populate function being called after the delay has passed. 
 
     function customerNameSearchTextbox_keyup() { 
 
      
 
      delay(function() { 
 
       if ($('#customerNameSearchTextbox').val().length > 0) { 
 
        customerNameUL_Populate(); 
 
        alert('dropdown'); //http://getbootstrap.com/javascript/#dropdowns 
 
        $('#customerNameSearchTextbox').dropdown(); <----- ? 
 
       } 
 
      else { 
 
        $('#customerNameUL').empty(); 
 
       }; 
 
      }, 500); 
 
     }; 
 

 
    //This function gets called to populate the list of customers for search 
 
     function customerNameUL_Populate() { 
 

 
      <working stuff> 
 
      
 
     };
 <div class="dropdown"> 
 
      <input type="text" id="customerNameSearchTextbox" class="form-control" placeholder="Customer" aria-describedby="basic-addon1" data-toggle="dropdown" onkeyup="customerNameSearchTextbox_keyup();" autocomplete="off"> 
 
      <ul class="dropdown-menu" aria-labelledby="dropdownMenu1" id="customerNameUL"> 
 
      </ul> 
 
     </div>

Путаница Я думаю, что у меня есть, с тем, что события для вызова, или какие классы назначить, или какие события для вызова. Предупреждение выше, показывая, что я получаю, где хочу, просто нужно заменить строку ниже, чтобы вызвать отображение customerNameUL.

+0

Я считаю - и это в основном только внешний вид и идут дела - что ваша проблема в первую очередь вызвано тем, что код, который переключает падение вниз называется на щелчок через атрибут переключения данных ищет, что они используют. Если бы вы сказали, добавьте переключение данных к другому элементу, который не показан, и просто вызовите '$(). Dropdown()', чтобы вы могли делать то, что вы хотите – Jhecht

ответ

1

Мне пришлось немного изменить код, но основы здесь должны работать. Дайте знать, если у вас появятся вопросы.

function customerNameSearchTextbox_keyup() { 
 
    var $this = $(this); 
 
    //In jQuery, I use $this as a reference to the jQuery-wrapped this object 
 
    var $parent = $this.parent('.dropdown'); 
 
    //Similar naming convention as $this. this is the parent object of our element, wrapped in jquery 
 

 
    if ($this.val().length > 0 && !$parent.hasClass('open')) { 
 
    //This if statement says: 
 
    //"If this value's length is gerater than 0 
 
    //AND the parent of this object does not have the 'open' class on it 
 
    //Continue with this code block: 
 
    $this.siblings('span.toggle-helper').dropdown('toggle'); 
 
    //searches for a sibling-level element that matches the CSS query 'span.toggle-helper', and fires the dropdown toggle method (showing it) 
 
    } else if ($this.val().length == 0) { 
 
    //If either one of those two requirements in the previous if is false, we end up here, where we only execute this code value's length is equal to 0. 
 
    $('#customerNameUL').empty(); 
 
    }; 
 

 
}; 
 

 
$(function() { 
 
    //$(function()....) is a shorter way to write $(document).ready(function()...); 
 
    $('#customerNameSearchTextbox').on('keyup', customerNameSearchTextbox_keyup); 
 
    //I did this because I was getting some weird sandbox errors leaving it as an 
 
    //attribute, but on an actual webpage (and not a snippet or fiddle) leaving 
 
    //this portion out and having the onkeyup="" attribute should be fine 
 
})
.toggle-helper { 
 
    display: none; 
 
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 
<div class="dropdown"> 
 
    <input type="text" id="customerNameSearchTextbox" class="form-control" placeholder="Customer" aria-describedby="basic-addon1" autocomplete="off" /> 
 
    <span class="toggle-helper" aria-haspopup="true" aria-expanded="false" data-toggle="dropdown">hi</span> 
 
    <ul class="dropdown-menu" aria-labelledby="dropdownMenu1" id="customerNameUL"> 
 
    <li>Lorem ipsum.</li> 
 
    <li>Doloremque, quam.</li> 
 
    <li>Iure, vel!</li> 
 
    <li>Culpa, rerum!</li> 
 
    </ul> 
 
</div>

+0

Я считаю, что понимаю, я делаю там, мой вопрос - где мой звонок для customerNameUL_Populate(); войдите в свою функцию customerNameSearchTextbox_keyup()? –

+0

Это зависит от многого. Если результаты, как правило, бывают быстрыми (вы бы знали лучше, чем я), то я бы сказал, начните его при запуске кода (ваша страница на стороне сервера должна быть в состоянии проверить, что строка пуста и просто ничего не возвращает довольно быстро), но реально вы можете запустить его в блоке кода «if» и перейти оттуда. Поскольку я не знал, что это за код, было сложно работать с ним, поэтому я просто отказался от некоторых опций. – Jhecht

+0

хотя, возможно, вы могли бы использовать websocket (я не знаю, каковы ваши результаты и как долго они будут, поэтому было бы лучше добавить их в список по одному за раз, когда браузер получит его, чем ждать дольше и получить их все сразу, в этот раз пользователь продолжает печатать) – Jhecht