In-Page Result Live Search

那年仲夏 提交于 2019-12-13 05:24:13

问题


I need a search box that would throw a result just like how the CTRL+F works. Right now, on my index.php page I have the ff format:

<table width="100%">
<thead>
<tr>
<th><strong>Client Name:</strong></th>
<th><strong>Nationality:</strong></th>
<th><strong>Birthday:</strong></th>
<th><strong>Address:</strong></th>
<th><strong>Gender:</strong></th>
<th><strong>Birthplace:</strong></th>
</tr>
</thead>
<?php

$sql=mysql_query(" select * from tenant order by id asc");
$count=0;
while($row=mysql_fetch_array($sql))
    {
    $client_id  =   $row['id'];
    $clientName =   $row['cname'];
    $cbday      =   $row['bday'];
    $cadd       =   $row['address'];
    $cgender    =   $row['gender'];
    $cbirth     =   $row['birthplace'];

        if($count%2)
        {
        ?>
        <tbody>
        <?php } else { ?>
        <tr id="<?php echo $id; ?>">
        <?php } ?>
        <td>
        <span class="text"><?php echo $client_id.".  ".$clientName; ?></span>
        </td>
        <td>
        <span class="text"><?php echo $cbday; ?></span> 
        </td>
        <td>
        <span class="text"><?php echo $cadd; ?></span>
        </td>
        <td>
        <span class="text"><?php echo $cgender; ?></span>
        </td>
        <td>
        <span class="text"><?php echo $cbirth; ?></span>
        </td>
        </tr>
        </tbody>
    <?php
    $count++;
    }//while-end
    ?>
 </table>

I've already tried many JQuery and Ajax tutorials but none of them seems to work fine with a value. So I just got into conclusion that perhaps those tutorials could only work only if you have a pre-defined value for the table rows. Like this one for example:

<th>ClientName</th>

Anyway I can have a CTRL+F like search on my index page for the table rows?


回答1:


Javascript, especially in combination with jQuery is very easy to learn and understand. No need for plugins or tutorials.

How to search the table?

Here is a jsfiddle I just wrote for you:

http://jsfiddle.net/j9U52/

$('#search-submit').on('click', function(event) {
    var v = $('#search-value').val(); // get the search value
    var t = $('.searchable td'); // WHERE to search
    var c = 'highlight'; // css class to add to the found string

    // for each td in the table
    $.each(t, function(idx, el) {
        // find the keyword
        var regex = new RegExp("\\b" + v + "\\b", "gi");

        // replace it and add a span with the highlight class
        el.innerHTML = el.innerHTML.replace(regex, function(matched) {
            return "<span class=\"" + c + "\">" + matched + "</span>";
        });
    });
});

I did not add to reset the highlighted matches when you enter a new search keyword, I leave this up to you :-) Hint: Add something like t.removeClass(c);



来源:https://stackoverflow.com/questions/25133811/in-page-result-live-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!