根据表格外的文本框值突出显示表格单元格值

时间:2013-05-02 09:06:10

标签: jquery html-table textbox

当用户在文本框中键入文本时,我希望突出显示与文本框值匹配的所有表格单元格值....

<input type="text" id="txtsearch"/>  
<html>
<table id="table" style="height:350px;margin-left:1em;width:700px;">
    <!--this is my table header-->
    <tr style="display:table-row">
        <th class="checkbox"><input type="checkbox"/></th>
        <th class="Name">NAME</th>
        <th class="Score">SCORE</th>
        <th class="Email">EMAIL</th>
        <th class="Empty"></th>
    </tr>
    <tr>
        <!--tabledata-->
        <td ><input type="checkbox" /></td>
        <td >Vijay Prakash</td>
        <td >34</td>
        <td >vijay@gmail.com</td>
        <td ></td>
    </tr>
</table>
<input type="button" id="btnCalculate" value="Calculate"/>
<label>Average:</label>
<label id="lblAverage"></label>
<label>Max:</label>
<label id="lblMax"></label>
</form>
</html>   
</div> 

2 个答案:

答案 0 :(得分:1)

想象一下,您的文本框中包含“文本框”ID,所选单元格将使用“突出显示”CSS类:

$('#textbox').on('change', function() {
  var textboxValue = $('#textbox').val();
  $('#table td').each(function() {
    if ($(this).text() === textboxValue) {
      $(this).addClass('highlight');
    } else {
      $(this).removeClass('highlight');
    }
  });
});

jsFiddle上查看此操作。

如果您需要进行部分匹配,请使用以下内容替换if

if ($(this).text().indexOf(textboxValue) !== -1) {

如果你需要匹配从开头开始的字符串(不在另一个字符串中,如上例所示),请使用:

if ($(this).text().indexOf(textboxValue) === 0) {

答案 1 :(得分:0)

试试这个:

$(function(){
console.log('');
$('#txtsearch').on('input', function() {
  var textboxValue = $('#txtsearch').val();
  if(textboxValue.length>0)
  {
  $('#table td').each(function() {
    var filter = textboxValue.toString().toUpperCase();
    if ($(this).html().toString().toUpperCase().indexOf(filter) > -1) {
      $(this).addClass('highlight');
    } else {
      $(this).removeClass('highlight');
    }
  });
  }
  else
  {
  $('#table td').removeClass('highlight');
  }
});
});
.highlight
{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtsearch"/>  
<table id="table">
    <tr>
        <th>NAME</th>
        <th>SCORE</th>
        <th>EMAIL</th>
    </tr>
    <tr>
        <td >Vijay Prakash</td>
        <td >34</td>
        <td >vijay@gmail.com</td>
    </tr>
    <tr>
        <td >Neeraj Pathak</td>
        <td >100</td>
        <td >npathak56@gmail.com</td>
    </tr>
</table>

相关问题