开发者

Auto-Load a html table with combobox

开发者 https://www.devze.com 2023-04-07 04:24 出处:网络
I want to load different html tables when I select an option in my combobox. For example if I have a combobox with 4 categories (Cars, Bikes, Motorbikes and Airplanes) I would like that when I select

I want to load different html tables when I select an option in my combobox. For example if I have a combobox with 4 categories (Cars, Bikes, Motorbikes and Airplanes) I would like that when I select one of the options, the specifi开发者_开发百科c table loads... and the tables may be different in size (not all the tables are for example 3 rows and 3 cells, each one of the tables may not be the same in structure)

 <select name="um" id="um" class="select_opt">
 <option value="Car">Car</option>"
 <option value="Bike">Bike</option>"
 <option value="Motorbike">Motorbike</option>"
 <option value="Airplane">Airplane</option>"

 <table id="Car" cellspacing="0">

   <tr>
  <th scope="alt">Title 1</th>
   </tr>  
   <tr>
     <td>Something 1</td>
     <td>Something 2</td>
   </tr>
 </table>

I have the combobox and one of the tables, I would like to see that table when I select the "Car" option... the same with the rest of the options in the combobox.

How can I do this?


Here are two ways to do this, one with pure JavaScript (no library) and the other using jQuery.

The process involves hiding all the tables then based on the value of the selected option choose the correct table to show.

The example tables have various columns (1-4) since you mentioned your tables may be various sizes as well.

JavaScript only:

example jsfiddle

var tables = [
    document.getElementById('Car'),
    document.getElementById('Bike'),
    document.getElementById('Motorbike'),
    document.getElementById('Airplane')
];

document.getElementById('um').onchange = function() {
    // hide all tables
    for (var i in tables) {
        tables[i].style.display = "none";
    }
    // get selected value and show it's table
    var selectedValue = this[this.selectedIndex].value;
    if (selectedValue) {
        document.getElementById(selectedValue).style.display = "block";
    }
};

jQuery:

example jsfiddle

// reuse variable to hide all tables
var $tables = $('table');

// Combobox change event
$('.select_opt').change(function() {
    $tables.hide();
    $('#' + $(this).val()).show();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消