2013-11-22 67 views
1

我試圖將顯示/隱藏jQuery功能應用於html下拉框。我希望能夠隱藏一個選項並在選擇下拉選項時顯示另一個選項。這個jQuery使用正常的按鈕,但不是下拉菜單。jQuery顯示/隱藏使用選擇

<select style="margin-left:30px;"> 
    <option value="" selected="selected">Please select a region</option> 
    <option id="uk_btn" value="1">UK</option> 
    <option id="usa_btn" value="2">USA</option> 
</select> 

<script> 
    $("#usa_btn").click(function(){ 
     $("#usa_tbl").show(); 
     $("#uk_tbl").hide(); 
    }); 
</script> 
<script> 
    $("#uk_btn").click(function(){ 
     $("#uk_tbl").show(); 
     $("#usa_tbl").hide(); 
    }); 
</script> 

回答

1

,如果你有選擇沒有ID,那麼你可以嘗試

$('select').change(function(){ 
    var val = $(this).val(); 
    if(val == 2) { 
      $("#usa_tbl").show(); 
      $("#uk_tbl").hide(); 
    } else { 
      $("#uk_tbl").show(); 
      $("#usa_tbl").hide(); 
    } 
}); 

,或者您可以通過ID做

<select id="select_id" style="margin-left:30px;"> 

現在

$('#select_id').change(function(){ 
....same as previous 
}); 
+0

感謝您對每個片段的額外評論! – SamXronn

+0

welcome @ user1745014 –

1

根源:沒有ID匹配在你的js select

<select style="margin-left:30px;"> //id attribute is missing 

改用change事件處理

<select style="margin-left:30px;" id="usa_btn"> 

JS:

5

你需要把事件選擇框

$('select').change(function(){ 
    var val = $(this + 'option:selected').attr('id'); 
    if(val == 'uk_btn') { 
      $("#usa_tbl").hide(); 
      $("#uk_tbl").show(); 
    } elseif(val == 'usa_btn') { 
      $("#uk_tbl").hide(); 
      $("#usa_tbl").show(); 
    } 
}); 

您還可以查看使用複選框value

var val = $(this).val(); 
if(val == '1') { 
    $("#usa_tbl").hide(); 
    $("#uk_tbl").show(); 
} elseif (val == '2') { 
    $("#uk_tbl").hide(); 
    $("#usa_tbl").show(); 
} 
+1

uk_btn然後$( 「#uk_tbl」)顯示()。不隱藏(); –

+0

如果選擇了第一個選項「Please select a region」,那麼使用if(val =='uk_btn')代碼的解決方案可能會出錯。 –

+0

對不起,方向不對。感謝我編輯了它。 – Gautam3164

2

你可以這樣做:

// Cache the elements first 
var $usa_tbl = $("#usa_tbl"); 
var $uk_tbl = $("#uk_tbl"); 

// Add a change event handler for the select element 
$("#select_ID").change(function() { 
    if (this.value === '2') { 
     $usa_tbl.show(); 
     $uk_tbl.hide(); 
    } else if (this.value === '1') { 
     $uk_tbl.show(); 
     $usa_tbl.hide(); 
    } else { 
     $uk_tbl.hide(); 
     $usa_tbl.hide(); 
    } 
}); 

其中,select_ID是選擇元素的ID。

Fiddle Demo

1
<select id="country" style="margin-left:30px;"> 

然後

$("#country").change(function(){ 
    $('[id$="_tbl"]').hide(); 
    $('#' + this.value.replace('_btn', '_tbl')) .show() 
});