Sort via javascript function

Asked

Viewed 236 times

0

I have this function, in various parts of my code, that performs the filter of what was selected and as it was typed.

function myFunction() {
    var input, filter, table, tr, td, i, filtro;
    input = document.getElementById("busca");
    filter = input.value.toUpperCase();
    table = document.getElementById("tablepesquisa");
    tr = table.getElementsByTagName("tr");
    filtro = document.getElementById("filtroPesquisa").value;

    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[filtro];
        if (td) {
            if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}

But now I need to sort according to the filter. For example, if it is number, sort by number, if it is description, sort by description, so it always sorts by the way it is reported via C#. Is it possible ? I saw some of them,.

This is my HTML:

 <div class="modal fade" id="myModalPesquisa" role="dialog">
    <div class="modal-dialog modal-lg">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Pesquisar</h4>
            </div>
            <div class="form-group">
                <div class="row">
                    <div class="col-md-12">
                        <div class="col-sm-3">
                            <select id="filtroPesquisa" class="form-control">
                                <option value="1">Nome</option>
                                <option value="0">Código</option>
                            </select>
                        </div>
                        <div class="col-sm-7">
                            <input type="text" id="busca" placeholder="Pesquisa.." onkeyup="myFunction()" class="form-control uppercase" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="modal-body">
                    <div class="table-overflow col-sm-12">
                        <table class="table table-responsive table-hover" id="tablepesquisa">
                            <thead>
                                <tr>
                                    <th>Código</th>
                                    <th>Nome</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var item in Model.Fornecedor)
                                {
                                    <tr>
                                        <td>@item.Codigo</td>
                                        <td>@item.Nome</td>
                                        <td align="right">
                                            <a href="#" onclick="fecha();buscaFornecedor(@item.Id);" title="Selecionar"><i class="fa fa-check-circle fa-lg"></i></a>&nbsp;
                                        </td>
                                    </tr>
                                }

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
            </div>
        </div>
    </div>
</div>
  • What’s the doubt? the code you posted works.

  • I wanted to sort according to the filter. The way it orders, is the way I load the table initial.

  • Ahhh, order! See my answer.

1 answer

0

You transform the Htmlcollection of the <tr>s into an array, ignoring the first tr that is of the haeders, and use the Sort of the Array object with a function compare() comparing strings from the selected column in the filter:

function ordenar() {
    table = document.getElementById("tablepesquisa");
    trs = table.getElementsByTagName("tr");
    filtro = document.getElementById("filtroPesquisa").value;

    [].slice.call(trs, 1) // transforma num array a partir do índice 1 (2o. elemento)
    .sort(function(tr1, tr2) { // usa o sort() do array passando como argumento uma função 
        return compare(tr1, tr2, filtro); // que retorna o resultado da chamada a compare() definida abaixo
    }).forEach(function(val, index) {
        // para cada elemento do array ordenado faz o append do tr na tabela
        table.appendChild(val);
    });
}

function compare(tr1, tr2, filtro) {
    col1 = tr1.getElementsByTagName("td")[filtro].innerHTML.toLowerCase();
    col2 = tr2.getElementsByTagName("td")[filtro].innerHTML.toLowerCase();
    return col1.localeCompare(col2);
}

See working here: https://js.do/Mari/364247 Click the column header to sort.

Edit: the code in js.do is a little different from the one pasted here, since before I had done the sorting based on the filter, and there I did according to the header clicked.

  • I’ll test and tell you, thank you for now.

  • If the answer solved your problem, please accept it.

Browser other questions tagged

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