How to script auto-complete/increment

Asked

Viewed 205 times

2

There was a need to create a text field that would receive names of cities, however complete the word in the field when starting the first digítos.

I need some idea, function with Arrays literals, more or less so:

<script language="javascript">

function autocompletar()
{
cit = ["uberaba","araxa","colombia"];
str = document.all.txt.value;
for (var i in cit)
{
if (document.all.txt.value.length > 1)
{
str.match(document.all.txt.value=cit[i])
               {
            }
        }
    }
}

</script>

Dispenso Bibliotecas nothing personal, I just have no interest.

  • 2

    Do you really have to do this on your arm? If not, here are some implementations of what you need: https://twitter.github.io/typeahead.js/examples/ , https://jqueryui.com/autocomplete/

1 answer

0


Good guys, I did ...

First, an array is created, which will have its compact library where we place the data that will be used sequentially.

Soon after, in the function autocompletar(), defined that the city we want will be one of the three that are in the array, and this, in turn, will be represented by the text box. Soon after, already in the body, suffice create the text field, giving this, by the event onKeyup, the functionality of the function autocompletar().

//criando objetos array 
sigla = new Object();
valor = new Object();

//declarando array com valores iniciais
  sigla[0] = 1000

//acessando um valor do array
//expecificado diretamente com o operador colchete
sigla[1] = "gua"; valor[1] = "guaíra"

sigla[2] = "bar"; valor[2] = "barretos"

sigla[3] = "mig"; valor[3] = "miguelópolis"
 
function autocompletar()
{
str = document.getElementById('txt').value;

//Iterando sobre aspas duplas de um objeto usando o for..in:
for (var i in sigla)
{

//Acessando o valor de um array através da aspas duplas
if(str.match(sigla[i]))
{

//recuperando os valores de um array entre as aspas duplas
str = document.getElementById('txt').value=valor[i];
           }
      }
}
<input type="text" id="txt" onkeyup="autocompletar()"/>

Another alternative in this link, where I did something similar to this code above, just adapt and ready!

  • And how are you going to fill this matrix? By hand?

  • @Shutupmagda Well, yes! That was just an example while studying the language Javascript, As time went by I was improving the thing. Note the date of this topic, today I just updated putting the example of my answer in a "snippet". But if you know something about the subject or think you could improve it or give an answer at the time feel free to, despite being an old topic, I will be willing to give my vote if it is really good on the subject.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.