简体   繁体   中英

How to search cells in a HTML table using JavaScript?

I have the following table in this Fiddle .

As you can see, is a table with two columns each row and this table will be updated, in the future, with more two row columns.

My goal here is to use the search filter to show rows at the top of the table. You can see this functionality in the Fiddle. If you type: "Weekly" the rows Daily and Weekly will appear. But Daily first, not Weekly.

But what I want is everytime I find a cell with a certain word I want it to appear at the first cell of the table. In this case if I search "Weekly" I want that in the first cell of the first row.

How can I do this with JavaScript? Here I'll let my Javascript code (In Fiddle's too):

function search() {
  var input, checkfilter, filter, table, tr, td, i;
  input = document.getElementById("myInput");

  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

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

Thank you very much for your help. I really appreciate the job is doing here in Stackoverflow.

I don't understand if you are asking a question or proposing a solution?

getElementById('foobar') is a way to manipulate objects in the DOM. For example here is something I use to quickly set up a PR template:

function () {
    var e = document.getElementById('pull_request_body');
    if (e) {
        e.value += 'Insert pull request template here';
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM