Sort a column of a table alphabetically

0

I have the following table and its code and I want to sort the table alphabetically so as to get "AC / BD / IC" instead of what is.

//javascriptparaadicionarelementosfunctionadicionar(){vardisciplina=localStorage.setItem("Disciplina",document.getElementById("nomedisciplina").value);
            var nome = localStorage.getItem("Disciplina");
            var table = document.getElementById("myTable2");
            var row = table.insertRow(1);
            var cell1 = row.insertCell(0);
                cell1.innerHTML = nome;       
}

    // HTML ,  tabela e, botão e input
    <table id="myTable2">
      <thead>
        <tr>
            <th>Disciplina</th>
        </tr>
      </thead>
      <tbody>
        <tr>
        </tr>
      </tbody>
    </table>

Adicionar nome da disciplina: <input type="text" name="nome" id="nomedisciplina"  onkeypress="return onlyAlphabets(event,this);" >    
<button id ="adicionardisc" onclick="adicionar()">Adicionar disciplina</button><br>
    
asked by anonymous 07.12.2016 / 12:53

1 answer

1

This example is working, but I had to make some changes to your code, come on:

1 - Delete% empty% within your tr

2 - Change your variable tbody :

var table = document.querySelector("#myTable2 tbody");

3 - Change the value of the variable table :

var row = table.insertRow(0);

4 - Add the row function to your javascript:

function ordenar() {
    var values = [].slice.call(document.querySelectorAll('#myTable2 tbody tr')).map(function(el) {
        return '<tr>' + el.innerHTML + '</tr>';  
    });
    values = values.sort();
    document.querySelector('#myTable2 tbody').innerHTML = values.join('');
}

//javascript para adicionar elementos 

function adicionar() {
  var nome = document.getElementById("nomedisciplina").value;
  var body = document.querySelector("#myTable2 tbody");
  var row = body.insertRow(0);
  var cell1 = row.insertCell(0);
  cell1.innerHTML = nome;       
}

function ordenar() {
  var values = [].slice.call(document.querySelectorAll('#myTable2 tbody tr')).map(function(el) {
    return '<tr>' + el.innerHTML + '</tr>';  
  });
  values = values.sort();
  document.querySelector('#myTable2 tbody').innerHTML = values.join('');
}
<table id="myTable2">
      <thead>
        <tr>
            <th>Disciplina</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>

Adicionar nome da disciplina: <input type="text" name="nome" id="nomedisciplina" >    
<button id ="adicionardisc" onclick="adicionar()">Adicionar disciplina</button><br>

<button onclick="ordenar()">ORDENAR</button>
In the sort function I get all the ordernar() of the tr and put it in an array, then use the tbody function to sort the array, then join the array with sort() (transforms into string) and replace the contents of the join() tag.

    
07.12.2016 / 14:16