1

如果选择了“其他”选项,我有这个简单<select>的应该显示输入。但是,如果我打开/关闭选择,或选择任何其他选项,“其他”就会消失。

这就是我的意思:

<script type="text/javascript">
    $(document).ready(function(){
    var $milestones = $(".other"),
        $selector = $('#source');

    $selector.change(function() {
        var selected = $selector.find('option:selected').attr('class');

        $milestones.hide();
        $('#' + selected).show();
    });
});
</script>

下面是包含选择以及隐藏 div 以显示输入的 HTML:

<div class="field text">
    <label>Where did you hear about us?</label>
    <select name="source" id="source">
        <option value="Facebook">Facebook</option>
        <option value="Twitter">Twitter</option>
        <option value="Other" class="other">Other</option>
    </select>
</div>
<div class="field text">
    <div id="other" class="hideme">
        <label>Sources:</label><input type="email">
    </div>
</div>
4

2 回答 2

2

我猜你想在option.other被选中时显示输入。所以这里是代码:

$(document).ready(function(){    
    var $selector = $('#source');

    $selector.change(function() {
        var showOther = $('option.other').is(':selected');
        $('#other').toggle(showOther);
    });
});

为此,您应该从一开始就隐藏输入,并让其jQuery.toggle()完成工作。

.hideme {
    display: none;
}

http://jsfiddle.net/kWSrh/

于 2013-10-12T01:26:08.860 回答
1

您隐藏了.other元素而不是输入框。看看这些变化。

$(document).ready(function(){
  $('.hideme').hide();
  $selector = $('#source');

  $selector.change(function() {
    var selected = $selector.find('option:selected').attr('class');

    $('.hideme').hide();
    $('#' + selected).show();
  });
});

http://jsfiddle.net/sBw5X/

于 2013-10-12T01:22:36.340 回答