Home > database >  Find HTML Table header index
Find HTML Table header index

Time:05-17

I need to find .10,.20,.30 up to .50 In a table header. The search parameters are base on a formula and will eventually determine what column to filter. I found this snippet from a previous similar post, but when I insert my table, I would get no results.

What could be the correct way to find the correct table header?

$(function() {
  $('#search').click(function() {
    $('td').each(function(index) {
      if ($(this).text() == $('#lookup').val()) {
        console.log(index)
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table id="myTable">
  <tr  id="ecentric">
    <th style="width:8%;">Column</th>
    <th style="width:20%;">Plate/saddle</th>
    <th style="width:10%;">Beam Width</th>
    <th style="width:10%;">0</th>
    <th style="width:10%;">.10</th>
    <th style="width:10%;">.20</th>
    <th style="width:10%;">.30</th>
    <th style="width:8%;">.40</th>
    <th style="width:8%;">.50</th>

  </tr>
  <input type="text" id="lookup">
  <input type="button" id="search" value="search">

CodePudding user response:

  1. Add thead

  2. Search for th instead of td

  3. Cache the selected THs

  4. Be more specific with your selectors, use $('#myTable thead th') instead of $('th') since you might target unwanted TH Elements in your DOM

  5. You can even skip the first 3 using

     $('#myTable thead th:nth-child(n 3)')
       ...
       if (index !=-1) console.log(index 3)
    

$(function() {
  const $ths = $('#myTable thead th');
  $('#search').on("click", function() {
    $ths.each(function(index) {
      if ($(this).text() == $('#lookup').val()) {
        console.log(index)
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr  id="ecentric">
      <th style="width:8%;">Column</th>
      <th style="width:20%;">Plate/saddle</th>
      <th style="width:10%;">Beam Width</th>
      <th style="width:10%;">0</th>
      <th style="width:10%;">.10</th>
      <th style="width:10%;">.20</th>
      <th style="width:10%;">.30</th>
      <th style="width:8%;">.40</th>
      <th style="width:8%;">.50</th>
    </tr>
    </thead>
</table>
<input type="text" id="lookup">
<input type="button" id="search" value="search">

  • Related