javascripthtml-table

Dropdown Selection for a table


I am trying to create a dropdown selector for a table. It is not selecting and I am still rather new to javascript.

Here is the snippet I was working on.

$('#vehicleSelect').change( function(){
  var selection = $(this).val();
  var dataset = $('#vehicleTable tbody').find('tr');
  
  dataset.each(function(index) {
    item = $(this);
    item.hide();
    
    var firstTd = item.find('td:first-child');
    var text = firstTd.text();
    if text == selection {
        item.show();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id='vehicleSelect'>
   <option value="">Please Select</option>
   <option value='SPARC'>SPARC</option>
   <option value='CIO_SP3_SB'>CIO_SP3_SB</option>
   <option value='CIO_SP3'>CIO_SP3</option>
   <option value='T4NG'>T4NG</option>
</select>

<table id='vehicleTable'>
   <thead>
      <tr>
         <th>Contract Type</th>
         <th>Contract Number</th>
         <th>Contract Holder</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>SPARC</td>
          <td>Conract1</td>
          <td>Company1</td>
      </tr>
      <tr>
         <td>CIO_SP3_SB</td>
         <td>Conract2</td>
         <td>Company2</td>
      </tr>
      <tr>
         <td>T4NG</td>
         <td>Conract3</td>
         <td>Company3</td>
      </tr>
      <tr>
          <td>CIO_SP3</td>
          <td>Conract4</td>
          <td>Company4</td>
      </tr>
   </tbody>
 </table>


Solution

  • There seems to be nothing wrong in the code except no () in the if-condition.

    if (text == selection) 
    {
        item.show();
    }