简体   繁体   中英

Display table row based on the selected option of Select html tag

So I have tried to display the content of a table based on the country of a user. basically if a user selects the united states as option, he gets a table row containing US data displayed.. I used a select with options, and every option has the domain extension of country as a value ( for example, for Brazil option, the value is br : <option value="br">Brazil</option> , plus the table row for it has the same option value as an ID ( <tr id="br" style="display: none;">..</tr> )

Is there any script to display a country data once the user selects that country in the options ?

Thank you, and here's my code:

HTML:

<select id="data">
  <option value="#">Select a country ..</option>
  <option value="us">United States</option>
  <option value="es">Spain</option>
 <!-- more countries -->
</select>


<div id="container">

<table border="1">
 <tr>
  <td> Country </td>
  <td> Chance</td>
 </tr>
 <tr id="us"  style="display: none;">
  <td> United States </td>
  <td> 2.02 % </td>
 </tr>
 <tr id="es" style="display: none;">
  <td> Spain </td>
  <td> 2.12 % </td>
 </tr>
</table>

</div>

I tried the following:

Jquery:

$('#data').change(function() {
    $('tr#($(this).val())').css('display','block');
});

Regards,

Thank you!

Thats not the way to concatenate, try this instead:

$('#data').change(function() {
    $('tr#' + $(this).val()).css('display','block');
});

EDIT with the OP comment:

Add a class to all the TRs that should hide/show, and then:

<table border="1">
 <tr>
  <td> Country </td>
  <td> Chance</td>
 </tr>
 <tr class="hideShowTr" id="us"  style="display: none;">
  <td> United States </td>
  <td> 2.02 % </td>
 </tr>
 <tr class="hideShowTr" id="es" style="display: none;">
  <td> Spain </td>
  <td> 2.12 % </td>
 </tr>
</table>

$('#data').change(function() {
    $('.hideShowTr').css('display','none');
    $('tr#' + $(this).val()).css('display','block');
});

Try this:

$('#data').change(function() {
//Only show specific row    
$('tr#' + $(this).val()).show();
//hide other rows
$("tr:not(:#"+$(this).val()+")").hide(); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM