有条件地隐藏表中的输入

时间:2015-09-17 19:02:38

标签: javascript jquery

当我选择其他选项时,我尝试使用其他选项选择输入,输入应该变为可见,但是我希望它默认为隐藏,如果稍后再次更改选择,则应该重新隐藏。我已经尝试了==和literal ===并使用!=反转隐藏show命令而无需更改

目前我有

HTML:

<tr>
    <td colspan="3" align="center" border="1">Certification:</td>
    <td colspan="3" align="center" border="1">
        <select name="certname" id="certname">
            <option value=""> </option>
            <option value="State">State</option>
            <option value="Other">Other</option>
        </select>
        <input type="text" id="othercert" name="othercert" />
    </td>
</tr>

和JS:

$("#othercert").hide();

$(document).ready(function () {
    $("#certname select").change(function (e) {
        if ($(this).val() != "Other") {
            $("#othercert").hide();
        }
        else {
            $("#othercert").show();
        }     
    });
});

我不确定从哪里出发或出现问题 - 感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

您的change选择器错误。 select不是#certname的孩子,因此请更改为以下内容:

$("select#certname").change(function (e) {

http://jsfiddle.net/ndgadeb1/

此外,您需要将初始隐藏在文档就绪功能中:

  $(document).ready(function () {
      $("#othercert").hide();

但是如果您希望在页面加载时隐藏,那么您可以在CSS中执行此操作:

#othercert{
   display:none;
}

这样就可以在页面加载时赢得 flash

答案 1 :(得分:2)

您的选择器认为select#certname的孩子,而不是id。它应该是:

select#certname而非#certname select

JS Fiddle

$("#othercert").hide();

$(document).ready(function () {
    $("select#certname").change(function (e) {
        if ($(this).val() != "Other") {
            $("#othercert").hide();
        } else {
            $("#othercert").show();
        }
    });
});