Filter table with multiple radio inputs

痴心易碎 提交于 2019-12-24 10:57:27

问题


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


来源:https://stackoverflow.com/questions/19420792/filter-table-with-multiple-radio-inputs

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