如何从html表中获取列的所有元素并验证该列表中是否存在特定字符串

时间:2019-02-11 23:10:21

标签: javascript jquery html loops html-table

我有一个包含多个行和列的html表。我想通过列ID提取所有值,并与一些匹配的字符串进行比较。如果匹配,我要启用页面上的按钮。 您能否让我知道如何在$(document).ready函数中按ID引用该列。

Here is the table
  <table id="data" class="table">
     <thead>
     <tr class="DataT1">
        <th>Id</th>
        <th>Name</th>
        <th>Place</th>
    </tr>
 </thead>

 <th:block th:each="it : ${data}">
   <tr>
    <td th:text="${it.id}">id</td>
    <td th:text="${it.name}">name</td>
    <td th:text="${it.place}">place</td>
   </tr>
  </th:block>
 </table>   

按钮:           style =“ visibility:hidden”>提交

$(document).ready(function(){
//here i want to pull the place column and verify if one of the 
  places matches my input string enable submit button
 $("#submitbutton").css("visibility", "visible");

 }
}                         

2 个答案:

答案 0 :(得分:0)

此功能将获取您td内的所有信息,并搜索您要寻找的string

但是我无法理解您是搜索particular string而不是searching for an object

const addresses = [...document.querySelectorAll(".address")];


const serchFromList = (arr, str) => {
  return arr.map(el =>
    el = el.innerHTML
  ).filter(el => el === str)

}

console.log(serchFromList(addresses, "NY"))

/* in case you want a boolean you can use some*/

const isAddressExist = (arr, str) => {
  return arr.map(el =>
    el = el.innerHTML
  ).some(el => el === str)

}

console.log(isAddressExist(addresses, "NY"))
<table id="data" class="table">
  <thead>
    <tr class="DataT1">
      <th>Id</th>
      <th>Name</th>
      <th>Place</th>
    </tr>
  </thead>

  <th>
    <tr>
      <td>4545</td>
      <td>5454</td>
      <td>65687</td>
    </tr>
    <tr>
      <td>aziz</td>
      <td>david</td>
      <td>paul</td>
    </tr>
    <tr>
      <td class='address'>NY</td>
      <td class='address'>MTL</td>
      <td class='address'>BC</td>
    </tr>
  </th>
</table>

答案 1 :(得分:0)

如果您不想向Place单元格添加额外的属性,那么XPath应该可以很好地实现。只需找出Place列的位置并从<td>的相同位置获取文本即可。

// Get the table node first
let node = document.getElementById('data')

// Find out position of `Place` column
let nth = document.evaluate('count(//th[text()="Place"]/preceding-sibling::*)+1', node).numberValue

// Get all the place cell by the position
let placeCells = document.evaluate(`//td[position()=${nth}]`, node)


// Get all the place names
let places = [],
    placeNode = placeCells.iterateNext()

while (placeNode) {
  places.push(placeNode.textContent)
  placeNode = placeCells.iterateNext()
}

console.log(places)
// ['NYC', 'SF', 'LA']
<table id="data" class="table">
  <thead>
    <tr class="DataT1">
      <th>Id</th>
      <th>Name</th>
      <th>Place</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>0001</td>
      <td>Mary</td>
      <td>NYC</td>
    </tr>
    <tr>
      <td>0002</td>
      <td>John</td>
      <td>SF</td>
    </tr>
    <tr>
      <td>0003</td>
      <td>Bob</td>
      <td>LA</td>
    </tr>
  </tbody>
</table>