How do list sorted by letter?

Asked

Viewed 1,311 times

0

I suppose I have a list of names, at array in Javascript. But I’m looking for a way to do it in the suggestion box style, where you only press an alphabetical key inside the field and as soon as you see keyword hints referring to typed letter.

Here is a simple basic example of Sorted List in alphabetical order:

<script>
    letras = new Array("C","B","A");
    for (i=0;i<3;i++)
{ 
    letras.sort();
    document.write(+ i + " array: " + letras[i]);
    document.write("<br>"); 
}           
</script>

In this case, I want to do something dynamic from this simple example above that would be a page with campo + div = resultado(array)

Just type a letter and it would be shown only whose name starts with the letter no matter the position of the vetor / array ignoring the display of others within the div. Good people, the logic is this, if someone can give me tips and/ or simple examples will be of great help.

2 answers

3


Do something like this:

letras.filter(function(item){
   var inputValue = document.getElementByid('id').value;
   var regex = new RegExp(inputValue);
   return item.match(regex);
});

Take a look at the example: https://jsfiddle.net/mgv2uyw1/ This is +- as it should be done, you can elaborate more the regularExpression to stay in a way that you prefer.

  • I believe that to stay 100% would have to change the REGEX to '/'+inputValue+'.*/i', if keep this way, will only return item that are exactly equal to inputValue.

  • 2

    RegExp('^'+inputValue+'.*', 'i');

  • I did tests and apparently qndo vc creates as new Regexp does not need the '/' '/' look at fiddle, but as I said, need to improve regexp to meet exactly the need

  • That I also forgot I didn’t need, but the regex is the one I put on top.

  • It will depend on what he will want to do, so it will pick up only when starting with the right string?(I am not CRANIO in regex rs forgive ignorance) I did a test without Pattern or anything, just using the string for example with "a" only it will pick up all the words that have "a" anywhere, already with "buf" he brought only the Bufalo. but thank you for supplementing the answer

0

Based on this as an initial basis, I successfully conclude this achievement, which I intended. Now, I share with you.

Suggestion Box - List Sorted by Letter, in order to have an idea of how this effect can be achieved, put the complete code as an example for study and/or research by other users.

<!DOCTYPE html>
<html>

<head>

<title>Caixa de Sugestao - Lista Ordenada por Alfabeto</title>

<style>

 	.campo
{
   	color:#333;
   	width:320px;
   	height: 32px;
   	border:1px solid #ccc;
   	font-family: "tahoma";
   	font-size: 11pt;
   	text-vertical:top;
   	padding:7px 5px 7px 5px;
   	float:center;
}

.dicas
{	
   	width: 320px;
   	margin: 0 auto;
   	position: relative;
   	max-height: 100px;
   	border: 1px solid #999;
   	background-color: #fff;
   	overflow:auto;
}
</style>

<script>

<!--// Bloco 1 - rotina 2 em 1 - Validar Campo & Exibir/Fechar Div //-->

function validar(){
document.getElementById('1').style.display='block';
if(document.getElementById('txt').value.length < 1){ 	//Esta linha ira validar se uma tecla foi pressionada dentro do campo
document.getElementById('1').style.display= "block";
document.getElementById('txt').focus();
return false
}
document.getElementById('1').innerHTML = "";
}

<!--// Bloco 2 - Listagem de Nomes - Ordenada por Letras do Alfabeto //-->

function lista(){
letras = ["Alex","Adrian","Adriano","Alexander","Alessandro","Ana","Aline","Ãgata","Alice","Amanda","Bryan","Breno","Bruno","Bernardo","Benjamin","Bruna","Belisa","Brenda","Bárbara","Beatriz","Caio","Cauê","Cauã","Carlos","Cléber","Carol","Clara","Camila","Carolina","Clarissa","David","Diego","Diogo","Danilo","Daniel","Dalila","Diana","Débora","Daniela","Eduardo","Elvis","Emanuel","Edson","Enzo","Eliza","Ãrica","Estela","Eduarda","Elizabeth","Felipe","Fábio","Fabiano","Francisco","Fernando","Felícia","Fabíola","Filipa","Flávia","Fabiana","Gabriel","Gustavo","Giovanni","Guilherme","Gregório","Gabriela","Giulia","Gisela","Graziela","Gabriele","Hugo","Hélio","Heitor","Hércules","Henrique","Helena","Heloísa","Igor","Inácio","Ivan","Ian","Iago","Ãris","Iara","Isa","Isadora","Isabel","Joaquim","Jonathan","José","jonas","joão","Jéssica","Joyce","Júlia","Juliana","Kevin","Kaio","Kelvin","Karina","kethlen","karen","kelly","Lucas","Leandro","Luciano","Lúcio","Lívia","Lis","Lilian","Letícia","Larissa","Matheus","Marcos","Miguel","Michel","Manuel","Marina","Mariana","Melissa","Marília","Micaela","Natanael","Nicolas","Natan","Nataniel","Nilton","Nara","Nina","Núbia","Natacha","Oliver","Otávio","Orlando","Olívia","Pedro","Paulo","Pablo","Paula","Pietra","Priscila","Paloma","Patrícia","Rafael","Ricardo","Rodrigo","Rômulo","Ronaldo","Reinaldo","Rafaela","Rúbia","Raquel","Rita","Rebeca","Samuel","Sérgio","Santiago","Sabrina","Serena","Sara","Sofia","Samara","Tiago","Tomás","Túlio","Theo","Thiago","Tabita","Tamara","Taís","Tamires","Talita","Ulisses","Umberto","Ueber","Victor","Vinicíus","Vagner","Violeta","Vitória","Valesca","Vanessa","Valquíria","Wanessa","Walter","Wilton","Yudi","Yuri","Yago","Yan","Yara","Yohana","Yasmin","Zoe"];
letras.sort();
alfabeto = letras.filter(function(el){
campo = document.getElementById('txt').value;
regex = new RegExp('^'+campo+'.*','i');
return el.match(regex);
});

<!--// Percorrendo os elementos do Array, apos digitar a letra desejada //-->
<!--// Sera montada a tabela dinamica com os resultados dentro da Div //-->

for (var i in alfabeto){ 
    tabela = document.getElementById('1');
tabela.innerHTML += "<table width='100%'><tr><td>"+ alfabeto[i] +"</td></tr></table>";
}
}

<!--// Bloco 3 - Selecionar Linha da Tabela - Dando Cor ao Fundo da Linha ao Passar o Mouse //-->

window.onmouseover=function(){
td = document.getElementsByTagName('td');
for(i in td){
td[i].onmouseover=function(){ preto =this.style.backgroundColor='#999999'; document.getElementsByTagName('td') = preto }
td[i].onmouseout=function(){ branco =this.style.backgroundColor='#fff'; document.getElementsByTagName('td') = branco  }
td[i].onclick=function(){ valor = this.innerHTML; document.getElementById('txt').value = valor; alert( "Oi " + valor + ", tudo bem!");}
}
}

</script>

</head>

<body>

<h2>Indice de Nomes</h2>

<h3>Lista de Nomes de A a Z</h3>

<h4>Digite uma letra abaixo:</h4>
<center>

<input onkeypress="validar()" class="campo" id="txt" value="" onkeyup="lista()" type="text">

<div id="1" class="dicas" style="display: none;" onclick="this.style.display='none';"></div>

</center>

</body>

</html>

w3schools - See a sample

Browser other questions tagged

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