2014-01-08 54 views
0

我有一個Bootstrap模態彈出窗口,它可以動態填充從數據庫創建的表格。它有一個SELECT元素,可以有可變數量的元素。該值包含季節代碼。顯示和隱藏SELECT變化動態創建的錶行

隨着表格的創建,每一行都會被賦予一個名爲「季節」的類,其中添加了季節代碼。最終的結果是,我們可以得到一個類列表看起來像這樣:

1季 season2

下面是代碼示例:

<select id="seaCombo"> 
    <option value="1">1 - Summer 2013</option> 
    <option value="2">2 - Fall 2013</option> 
    <option value="3">3 - Winter 2013</option> 
    <option value="4">4 - Spring 2013</option> 
    <option value="5">5 - Holiday 2013</option> 
</select> 

<table> 
    <tr class="season1"> 
    <td>Something here</td> 
    <tr> 
    <tr class="season2"> 
    <td>Something here</td> 
    <tr> 
    <tr class="season3"> 
    <td>Something here</td> 
    <tr> 
    <tr class="season4"> 
    <td>Something here</td> 
    <tr> 
    <tr class="season5"> 
    <td>Something here</td> 
    <tr> 
</table> 

我想要顯示在SELECT控件中選擇的季節並隱藏所有其他項。問題是表和選擇是動態的。因此,選擇可能只有2個季節列出,這意味着桌子只有兩個季節類別。選擇可能有4個季節列出,這意味着桌子將只有4個季節類。

我該如何編寫一些JQuery來顯示所選季節的類,但隱藏了表中的所有其他類?

+0

選項3,4和5的值是否正確? – next2u

+0

謝謝你的收穫!我編輯帖子以反映正確的值。 –

回答

1

試試這個,

$(function() { 
    $('#seaCombo').on('change', function() { 
     s = this.value; 
     $('tr').hide(); // first hide all rows 
     if ($('.season' + s).length) { // check the row-class exists or not 
      $('.season' + s).show(); // show only the seasonal row 
     } 
    }); 
}); 

Demo

+0

這個完美的作品!謝謝! –

1

這裏有:

$(document).ready(function() { 
    function showProperSeason() { 
     var seasonNumber = $('#seaCombo').val(); //Get the season number selected 
     $('table tr').hide(); //Hide all rows 
     $('.season' + seasonNumber).show(); // show only the seasonal row   
    } 

    $('#seaCombo').change(showProperSeason); 
    showProperSeason(); 
}); 

演示:http://jsfiddle.net/edgarinvillegas/e4s2J/3/

這樣你就會開始顯示選定的季節,也當你改變選擇。

乾杯