user3266259
user3266259

Reputation: 399

Filtering a table with javascript

I have an sql query that I'm echoing out as a table using php.

 $query="SELECT Name,
           Location,
           ID,
           Price

         From ProdTable
         where ID>=2300;"

$results = mysql_query($query);

while ($row = mysql_fetch_array($results)) {
    echo '<tr>';

    foreach($row as $field) {
        echo '<td>' . htmlspecialchars($field) . '</td>';
    }

    echo '</tr>';
}

What I want to do now is be able to filter the table using check boxes (showing all locations on default and then allowing the user to filter them as he/she pleases), like so:

<input type="checkbox" name="location" value="newyork">New York
<input type="checkbox" name="location" value="chicago">Chicago
<input type="checkbox" name="location" value="orlando">Orlando
<input type="checkbox" name="location" value="losangeles">Los Angeles

But I want to do this through javascript so it's more dynamic and the user wouldn't need to press submit in order for the filtering to take place. I know there are already javascript toolkits out there for filtering, but I wanted to write a few javascript functions myself.

Any guidance is greatly appreciated.

Upvotes: 0

Views: 144

Answers (3)

weeklyTea
weeklyTea

Reputation: 345

if you want to write function by yourself, here is an example of function using jQuery that could help:

$('#val1').change(function(){
    if (this.checked){
        $('table tr').each(function(){
            var td = $(this).find('td')
            if(td.html() == 'value1')
                td.show();
        })
    }else{
        $('table tr').each(function(){
            var td = $(this).find('td')
            if(td.html() == 'value1')
                td.hide();
        })
    }
})

Note: It is far from good way, just sample which must show how can it be solved.

Upvotes: 0

Amitesh
Amitesh

Reputation: 1517

You can adopt below basic approach
Match the checkboxes value with user entered value and set its (or parent tr) display none/table-row using javascript accordingly.

Upvotes: 0

Mohamad Shiralizadeh
Mohamad Shiralizadeh

Reputation: 8765

You can use phpGrid or jqGrid for ajax grid. it's easy to use.

Upvotes: 2

Related Questions