문제

I've got a table with a several columns and rows with an HTML5 data-attribute. After reading through quite a few SO questions and answers, I've tried to develop code that will allow live search of a table by text or data-attribute, but I'm stuck. I have gotten the same code to work on <li> elements (see that jsFiddle here), so I think my problem is with my jQuery selectors. Does anyone have suggestions on what I'm doing wrong?

HTML:

<input id="search" placeholder="search" />
<table>
    <tr>
        <th colspan="4">
            California
        </th>
    </tr>
    <tr>
        <td>Name</td>
        <td>Company</td>
        <td>Link</td>
        <td>Notes</td> 
    </tr>
    <tr data-state="california">
      <td>Joe Smith</td>
      <td>Acme</td>
      <td>www.www.com</td>
      <td>n/a</td>
    </tr>
    <tr data-state="california">
      <td>Sue Smith</td>
      <td>Acme</td>
      <td>www.www.com</td>
      <td>n/a</td>
    </tr>
    <tr data-state="california">
      <td>Frank Jones</td>
      <td>Etc</td>
      <td>www.www.com</td>
      <td>n/a</td>
    </tr>
    <tr>
        <th colspan="4">
            Alaska
        </th>
    </tr>
    <tr data-state="alaska">
      <td>Sue Henderson</td>
      <td>Acme</td>
      <td>www.com.com</td>
      <td>n/a</td>
    </tr>
    <tr data-state="alaska">
      <td>Jimmy Dean</td>
      <td>Acme</td>
      <td>www.com.com</td>
      <td>n/a</td>
    </tr>
</table>

jQuery:

$("input#search").keyup(function(){
        var filter = $(this).val();
        var regExPattern = "gi";
        var regEx = new RegExp(filter, regExPattern);   
        $("table tr").each(function(){
        if (
        $(this).text().search(new RegExp(filter, "i")) < 0 &&
        $(this).data('state').search(regEx) < 0 
        ){
                $(this).hide();
            } else {
                $(this).show();
            }        
        });
});

jsfiddle: http://jsfiddle.net/Q3cvH/17/

도움이 되었습니까?

해결책

You have 3 tr elements that do not have a data-state attribute which you cannot call .search on.

You should check if a data-state exist before trying to do .search on it like this:

if($(this).data('state'))

Demo.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top