PDKnight
PDKnight

Reputation: 722

Change input autocomplete value

I have another question: Is there any way to change input autocomplete value dynamically with javascript?

Example:

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

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

Google example: Google searching

Am I able to do it with plain JS? Any suggestion will be great :).

Upvotes: 0

Views: 3054

Answers (2)

jupeter
jupeter

Reputation: 746

I found

javascript : Auto complete javascript text field

if use existing library then

typeahead.js

typeahead.js / example

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++;  
        }
      
      }
     
    });
});
  
  }
}
.accItem{
  background-color:#333;
  color:#fff;
  width:200px;
}

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

suggestion--

  • condition in call ajax (slow with big data)
  • condition in send/receive data with ajax

hope help you this way...

Upvotes: 1

Tomas Kirda
Tomas Kirda

Reputation: 8413

It is possible, but you will need to write much more code. Your best option to use existing library that handles this for you:

Documentation: https://github.com/devbridge/jQuery-Autocomplete

Demo: http://devbridge.github.io/jQuery-Autocomplete/

Upvotes: 0

Related Questions