【问题标题】:Show/hide div if "other" radio OR checkbox is checked如果选中“其他”单选或复选框,则显示/隐藏 div
【发布时间】:2011-09-01 19:34:32
【问题描述】:

我意识到这与许多其他问题并没有太大的不同,但正是这些细微的差异让我觉得很棘手。

基本上,如果选中“其他”,我想显示或隐藏文本输入以指定“其他”选项。

我的方法似乎适用于复选框。但是当您取消选中其他单选按钮时,其他文本输入不会隐藏。我知道收音机的性质有点不同,但我不确定如何适应这一点。

这是代码,我还创建了一个jsFiddle,您可以在其中看到它的运行情况。感谢您的帮助!

HTML

<fieldset>
<h1>Pick One</h1>
<p><label><input value="1" type="radio" name="options"> Chicken</label></p>
<p><label><input value="2" type="radio" name="options"> Beef</label></p>
<p><label><input value="3" type="radio" name="options"> Fish</label></p>
<p><label><input value="4" type="radio" name="options" class="other"> Other</label></p>
<p class="specify-other"><label>Please specify: <input name="options-other"></label></p>
</fieldset>

<fieldset>
<h1>Pick Several</h1>
<p><label><input value="1" type="checkbox" name="food"> Rice</label></p>
<p><label><input value="2" type="checkbox" name="food"> Beans</label></p>
<p><label><input value="3" type="checkbox" name="food"> Potatoes</label></p>
<p><label><input value="4" type="checkbox" name="food" class="other"> Other</label></p>
<p class="specify-other"><label>Please specify: <input name="options-other"></label></p>
</fieldset>

jQuery

​​>
$('.other').click(function(){
    if ($(this).is(':checked'))
    {
        $(this).parents('fieldset').children(".specify-other").show('fast');
    } else {
        $(this).parents('fieldset').children(".specify-other").hide('fast');
    }
});

CSS

.specify-other {display: none;}

【问题讨论】:

  • 您可以将$(this).is(':checked') 更改为this.checked - 它更加更高效,并且语义相同。

标签: jquery


【解决方案1】:

这是我的方法:在整个广播“组”中工作:

$('input[name=options]').click(function(){
    if ($(this).hasClass('other')) {
      $(this).parents('fieldset').children(".specify-other").show('fast');
    } else {
      $(this).parents('fieldset').children(".specify-other").hide('fast');
    }
})

【讨论】:

  • 我做了一个调整:将我的选择器更改为'input:radio, input:checkbox'。这似乎做到了!谢谢!
  • 实际上,我的调整不适用于复选框。它有点扭转了我原来的问题!我想我可能必须将这两种方法结合起来。
【解决方案2】:

好的 每当您单击单选按钮时,它总是选中,它不像复选框来选中或取消选中单击。

您已检查具有某些条件的单选按钮作为所有单选按钮的组,因此请检查值,如果选中 value=4,则显示其他希望隐藏

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2017-02-04
    • 2023-02-06
    • 2015-02-21
    相关资源
    最近更新 更多