更改输入自动完成值

时间:2015-02-14 15:22:27

标签: javascript input autocomplete

我有另一个问题:有没有办法用javascript动态更改输入自动完成值?

示例:

<input id="myInput" 
       placeholder="Write something here..." 
       onchange="changeAutocompleteValue(event)">

<script>
    function changeAutocompleteValue(event)
    {
        var list = ["first", "second", "third"];
        event.list = list;
    }
</script>

Google示例: Google searching

我能用普通的JS做到吗?任何建议都会很棒:)。

2 个答案:

答案 0 :(得分:1)

我找到了

javascript : Auto complete javascript text field

如果使用现有的库那么

typeahead.js

typeahead.js / example

&#13;
&#13;
function loadXMLDoc(_target, _type,_func) {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 ) {
           if(xmlhttp.status == 200){
               
             
              data = JSON.parse(xmlhttp.responseText);
             
              _func(data);

           }
           else if(xmlhttp.status == 400) {
              alert('There was an error 400')
           }
           else {
               alert('something else other than 200 was returned')
           }
        }
    }

    xmlhttp.open(_type, _target, true);
    xmlhttp.send();
}

function ontxtChange(){
 var dcc = document.getElementById('autocc');
  var dc = document.getElementById('autoc');
  dcc.innerHTML = ' ';
 var i = 0;
var target = "https://api.github.com/users/mralexgray/repos"


// 

if(dc.value.length > 0){
  
  
loadXMLDoc(target,'GET',function(data){
    data.forEach(function(x){
      
      if(i < 10){
        
        if(x.name.toLowerCase().indexOf(dc.value.trim()) != -1){
              dcc.innerHTML += '<p class="accItem">' + x.name.toLowerCase() + '</p>';
         i++;  
        }
      
      }
     
    });
});
  
  }
}
&#13;
.accItem{
  background-color:#333;
  color:#fff;
  width:200px;
}

#autocc{
 width:200px;
}
&#13;
<body>
<input type="text" id="autoc" onkeypress="ontxtChange()" > example : "am"
<div id="autocc">
  
</div>
</body>
&#13;
&#13;
&#13;

建议 -

  • 调用ajax中的条件(大数据缓慢)
  • 使用ajax
  • 发送/接收数据的条件
希望以这种方式帮助你...

答案 1 :(得分:0)

这是可能的,但您需要编写更多代码。您最好的选择是使用现有的库来为您处理:

文档:https://github.com/devbridge/jQuery-Autocomplete

演示:http://devbridge.github.io/jQuery-Autocomplete/