Search code examples
javascriptjqueryjquery-selectorsjquery-filter

jQuery - selector inside another selector - passed in variable loses its value and becomes an indexer?


I'm somewhat new to jQuery and am just wondering how I go about passing in a string value rather than what appears to be a reference to a jQuery item from a selector? I'm having a hard time explaining so here's a sample demo. Don't even know what to title this so please have at editing the title if you can think of a better one.

At the line where I do $("td").filter(function(str){ the str that is passed in becomes an index position of which TD I'm in. So while debugging the first time in it's a 0 the next time a 1 and so on. I tried google but I'm not even sure what to search for, any documentation/code help would be much appreciated

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("select[name='showTeam']").change(function () {
            $("select[name='showTeam'] option:selected").each(function () {
                var str = $(this).val().toLowerCase();
                //str = what it was set to up there
                //alert(str);
                $("td").filter(function(str) {
                    //str = becomes a number = to position of TD.. ie for 5th TD match STR = 4 (starts at index 0)
                    return $(this).text().toLowerCase().indexOf(str) != -1;
            }).css('background','red');
        });
    })
});
</script>
Show Team: <select id="showTeam" name="showTeam">
    <option>All</option>
    <option>Chelsea</option>
    </select>

<div id="games">
  <table border="1">
  <tbody>
  <tr>
    <th>ID</th>
    <th>Game date</th>
    <th>Field</th>
    <th>Home team</th>
    <th>Home team score</th>
    <th>Away team</th>
    <th>Away team score</th>
    <th>Game type</th>
  </tr>
  <tr class="odd_line" id="game_460">
    <td>459</td>
    <td>03 Nov 19:00</td>
    <td>Field 2</td>
    <td>Madrid </td>
    <td>3</td>
    <td>Bayern Munich </td>
    <td>1</td>
    <td>Season</td>
  </tr>
  <tr class="odd_line" id="game_461">
    <td>460</td>
    <td>03 Nov 19:00</td>
    <td>Field 3</td>
    <td>chelsea</td>
    <td>5</td>
    <td>arsenal</td>
    <td>4</td>
    <td>Season</td>
  </tr>
</div>

Solution

  • $(document).ready(function(){
        $("#showTeam").change(function () {
            var searchFor = $(this).val().toLowerCase();
            $("#games table tbody tr td:contains('" + searchFor + "')").parent().css('background','red');
        })
    });
    

    Demo