Filter table with multiple radio inputs

2019-08-05 07:26发布

问题:

All I want is filter the table with radio inputs. This is my jsfiddle

I am using this inputs and table:

<div style="border:1px solid;">
<input  type="radio" id="Bob" name="name"  />Bob
<input type="radio" id="Jay" name="name"  />Jay
</div>
<div style="border:1px solid; margin:5px 0;">
<input type="radio" id="developer" name="position" />Developer
<input type="radio" id="itManager" name="position" />Manager
</div>
<table border="1" style="text-align:center;">
    <tr>
        <th>Name</th><th>Position</th>
    </tr>
    <tr>
        <td>Bob</td><td>Developer</td>
    </tr>
    <tr>
        <td>Jay</td><td>Manager</td>        
    </tr>
    <tr>
        <td>Bob</td><td>Manager</td>
    </tr>
    <tr>
        <td>Jay</td><td>Developer</td>        
    </tr>
</table>

and this js:

 $('#Bob').change( function() {
     $('tr').show();
     $('tr:not(:has(th)):not(:contains("Bob"))').hide();
 });

 $('#Jay').change( function() {
     $('tr').show();
     $('tr:not(:has(th)):not(:contains("Jay"))').hide();
 });

 $('#developer').change( function() {
     $('tr').show();
     $('tr:not(:has(th)):not(:contains("Developer"))').hide();
 });

 $('#itManager').change( function() {
     $('tr').show();
     $('tr:not(:has(th)):not(:contains("Manager"))').hide();
 });

All I need is double filter, when I select Bob, its shows only bobs than when I select Developer I want to see Bob - Developer tr.

I know js code is wrong but I wanted you make understand what I want to do.

回答1:

Try this, more simple:

$('input[type="radio"]').change(function () {
    var name = $('input[name="name"]:checked').prop('id') || '';
    var position = $('input[name="position"]:checked').prop('id') || '';
    $('tr').hide();
    $('tr:contains(' + name + ')').show();
    $('tr').not(':contains(' + position + ')').hide();
});

Demo here

The only change in the HTML you need is to have the ID of the position radio buttons to be the same as the table. The that information can be used in the tr show/hide. Like:

<input type="radio" id="Developer" name="position" />Developer
<input type="radio" id="Manager" name="position" />Manager