jQuery使用select显示/隐藏

jQuery show/hide using select

本文关键字:隐藏 显示 select 使用 jQuery      更新时间:2023-09-26

我正在尝试将显示/隐藏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>

您需要将事件放入类似的选择框

$('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();
}

您可以这样做:

// 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演示

如果您在select上没有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
});

根本原因: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();
    });
<select id="country" style="margin-left:30px;">

然后

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