Home > Enterprise >  How can I show only table rows that contains a radio button value?
How can I show only table rows that contains a radio button value?

Time:11-09

I have for example three radio button like this:

0-3030-9090-100

and table :

id name età
1 Sta 0-30
2 Danny 30-90
3 Elle 90-100

JSFiddle: https://jsfiddle.net/Carla102030/28r7oxwf/5/

My goal is: when users checked first radio button, in the table he must see only rows with this value and so on. So I want a JS function that works in this way.

Can you help me please?

CodePudding user response:

You can use jQuery filter function to detect the value.

$(document).ready(function(){
  $('input[name="filter"]').change(function(){
    var value = $(this).val().toLowerCase();
    if (value === "all"){
      $("#myTable tr").show();
    } else {
      $("#myTable tr").filter(function() {
        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
      });
    }   
  });
});
.table{
  width: 100%;
  border: 1px solid #ddd;
}

.table tr, .table th, .table td{
  border: 1px solid #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="radioCont">
  <input type="radio" name="filter" value="0-30" id="i1" /> <label for="i1"> 0-30</label> <br />
  <input type="radio" name="filter" value="30-90" id="i2" /> <label for="i2"> 30-90</label> <br />
  <input type="radio" name="filter" value="90-100" id="i3" /> <label for="i3"> 90-100</label> <br />
  <input type="radio" name="filter" value="all" id="i4" checked /> <label for="i4"> All</label> <br />
</div>

  <table class="table">
    <thead>
      <tr>
        <th>id</th>
        <th>name</th>
        <th>età</th>
      </tr>
    </thead>
    <tbody id="myTable">
      <tr>
        <td>1</td>
        <td>Sta</td>
        <td>0-30</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Danny</td>
        <td>30-90</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Elle</td>
        <td>90-100</td>
      </tr>
    </tbody>
  </table>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related