我可以根据所选值显示/隐藏元素吗?

can i show/hide elements depending on the selected value?

本文关键字:隐藏 元素 显示 我可以      更新时间:2023-09-26

这是应该发生的事情:如果选择值"NL",则"地点"和"街道"字段不是必需的。它应该被隐藏。当选择值"BE"时,它应该显示"地点"和"街道"字段/行(带有类for-be(。默认情况下,它应该被隐藏,因为默认情况下选择了"NL"。

<table>
<tbody>
<tr>
    <td>
        <label>Country: </label>
    </td>
    <td>
        <select name="country" id="Select">
            <option value="NL">Netherlands</option>
            <option value="BE">Belgium</option>
        </select>
    </td>
</tr>
<tr>
    <td><label>Zipcode: </label></td>
    <td><input type="text" name="zipcode" maxlength="6"></td>
</tr>
<tr class="for-be">
    <td><label>Place: </label></td>
    <td><input type="text" name="place" maxlength="60"></td>
</tr>
<tr class="for-be">
    <td><label>Street: </label></td>
    <td><input type="text" name="street" maxlength="60"></td>
</tr>
<tr>
    <td><label>Number: </label></td>
    <td><input type="text" name="number" maxlength="5"></td>
</tr>
</tbody>
</table>

jQuery中的代码我有:

$(document).ready(function(){
    var select = $('#Select');
    if(select.val() == 'NL'){
        $('.for-be').hide();
    }
    select.change(function(){
        if(select.val() == 'NL'){
            $('.for-be').hide();
        } else if(select.val() == 'BE'){
            $('.for-be').show();
        }
    });
});

它不是这样工作的。编辑:它以这种方式工作(添加了缺少的"(;"(

http://codepen.io/anon/pen/JGzEKJ

select.change(function(){
  var selectedV = $('option:selected',this).attr('value');
  if(selectedV == 'BE'){
    $('.for-be').hide();
  }else {
    $('.for-be').show();
  }
});

只需尝试实现简单的逻辑。

.HTML:

<table>
<tbody>
<tr><td><label>Country: </label></td><td><select name="country" id="Select"><option value="NL">Netherlands</option><option value="BE">Belgium</option></select></td></tr>
<tr><td><label>Zipcode: </label></td><td><input type="text" name="zipcode" maxlength="6"></td></tr>
<tr class="BE all_value"><td><label>Place: </label></td><td><input type="text" name="place" maxlength="60"></td></tr>
<tr class="BE all_value"><td><label>Street: </label></td><td><input type="text" name="street" maxlength="60"></td></tr>
<tr><td><label>Number: </label></td><td><input type="text" name="number" maxlength="5"></td></tr>

</tbody>
</table>

Jquery

$(document).ready(function(){
    var select = $('#Select');
    select.change(function(){
     $(".all_value").hide();
     $("."+select.val()).show();
    }
});

试试 select.on((。这是一个工作小提琴

https://jsfiddle.net/57gok7c9/

select.on('change',function(){
    if(select.val() == 'NL'){
        $('.for-be').hide();
    } else if(select.val() == 'BE'){
        $('.for-be').show();
    }
});

编辑 - 正如 satpal 指出的那样,您的代码中有一个简单的语法错误。

试试这个

$('#Select').change(function () {
var textVal= $(this).val();
if (textVal== 'NE') {
     $('.for-be').hide();
}
else if(textVal=='BE') {
     $('.for-be').show();
}
});