如何在文本字段中键入内容时显示下拉框

时间:2017-08-19 19:14:20

标签: javascript jquery html css

是否有select标签的点击监听器? 如何触发选择标记并显示下拉框? 像这样here

function myFunction(obj) {
  var dropdown= document.getElementById("dropdown");
  dropdown.click(); ???
}
<div class="dropdown">
  <input type="text" onkeyup="myFunction()"/>
  <select id="dropdown" onchange="this.previousElementSibling.value=this.value; this.previousElementSibling.focus()">
     <option>1</option>
     <option>2</option>
     <option>3</option>
  </select>
</div>

3 个答案:

答案 0 :(得分:1)

您可以执行以下操作: -

&#13;
&#13;
$(document).ready(function(){
  $('input[type="text"]').on('keyup',function(){
   $('#dropdown').attr('size',$('#dropdown option').length);
  }); 
});
&#13;
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="dropdown">
    <input type="text"/><br><br>
    <select id="dropdown">
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>
</div>
</body>
</html>
&#13;
&#13;
&#13;

注意: - 您可以使用下面的第三方插件

editable-select

工作示例: -

&#13;
&#13;
$(document).ready(function(){
  $('input[type="text"]').on('keyup',function(){
   $('#dropdown').editableSelect('show');;
  }); 
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
<link href="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet">

<div class="dropdown">
    <input type="text"/><br><br>
    <select id="dropdown">
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你不能用selctbox真正做到这一点。一种解决方法是将selectbox大小设置为大于0的数字。您可以展开它以获得selectbox的精确高度(=选项数)并将其设置为属性大小:

$(document).ready(function(){
  $('input[type="text"]').on('keyup',function(){
    $('#dropdown').focus().attr('size', 3);
  }); 
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="dropdown">
    <input type="text"/>
    <select id="dropdown">
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>
</div>


</body>
</html>

答案 2 :(得分:1)