jQuery使用select显示/隐藏

时间:2013-11-22 10:12:54

标签: javascript jquery html

我正在尝试将show / hide jQuery函数应用于html下拉框。我希望能够隐藏一个选项,并在选择下拉选项时显示另一个选项。这个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>

5 个答案:

答案 0 :(得分: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 :(得分: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是select元素的ID。

Fiddle Demo

答案 2 :(得分:1)

根本原因:您的js中select没有 id 匹配。

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

而是使用 change 事件处理程序

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

<强> JS:

 $("#usa_btn").change(function(){
      alert($(this).val());  // to get the value of selected option based on it 
                             // add your condition
      $("#usa_tbl").show();
      $("#uk_tbl").hide();
    });

答案 3 :(得分: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
});

答案 4 :(得分:1)

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

然后

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