Sort Names - JavaScript

0

I need to create an HTML document where the user can add names in a numbered list (OL). Your document should have a text box (an input for entering text) where the user can enter one name at a time. In addition, you must have a button labeled "Add", which, when clicked, adds the text you typed into the OL list. The user can add as many names as he wants and each name is added at the end of the OL list. However, at any time during execution, the user can sort the OL list names by clicking a button labeled "Sort List". The user clicks the "Sort List" button, it must be regrouped in an orderly manner. Use the sorting algorithm of your choice (Bubble, Insertion, Quick, etc.).

z code it at the time of sorting I think it identifies the scale as another variable and divides.

<!doctype HTML>
<html>
<head>
    <title>Eventos em javascript</title>
    <meta charset="utf-8" >
    <script>
        var arr = [];
        function adicionar(){

    var nome = document.getElementById("nome");

    lista.innerHTML = lista.innerHTML + "<li>" + nome.value + "</li>";
    arr = arr + nome.value + " ";
}
    function ordenar(){
    document.getElementById("lista").innerHTML = "";
    var iv = arr.split(" ");
    iv.pop();
    iv.sort();
    for (var i = 0 ; i < iv.length ; i++) 
    {
        lista.innerHTML = lista.innerHTML + "<li>" + iv + "</li>";
    }
}
</script>
</head>
<body>
<header>
    <h3>Lista de Nomes</h3>    
</header>
<input id="nome" type="text">
<button onclick="adicionar()">Adicionar</button>
<ol id="lista">
</ol>
<button onclick="ordenar()">Listar por ordem alfabética</button>
<div class="col-sm-10">

</div>
</body>
</html>
    
asked by anonymous 03.07.2017 / 22:50

1 answer

0

Just change this line

lista.innerHTML = lista.innerHTML + "<li>" + iv + "</li>";

for this

lista.innerHTML = lista.innerHTML + "<li>" + iv[i] + "</li>";

to loop (iterate) the array already ordered iv.sort(); and print the result

var arr = [];
function adicionar(){
   var nome = document.getElementById("nome");
   lista.innerHTML = lista.innerHTML + "<li>" + nome.value + "</li>";
   arr = arr + nome.value + " ";
}

function ordenar(){
   document.getElementById("lista").innerHTML = "";
   var iv = arr.split(" ");
   iv.pop();
   iv.sort();
   for (var i = 0 ; i < iv.length ; i++) 
   {   
     lista.innerHTML = lista.innerHTML + "<li>" + iv[i] + "</li>";
   }
}
<header>
    <h3>Lista de Nomes</h3>    
</header>
<input id="nome" type="text">
<button onclick="adicionar()">Adicionar</button>
<ol id="lista">
</ol>
<button onclick="ordenar()">Listar por ordem alfabética</button>
<div class="col-sm-10">

</div>
    
04.07.2017 / 00:48