jquery - 如果选中 "other"单选或复选框,则显示/隐藏 div

标签 jquery

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

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

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

这是代码,我还创建了一个 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;}

最佳答案

这是我的方法:在整个 radio “组”上工作:

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

关于jquery - 如果选中 "other"单选或复选框,则显示/隐藏 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6125738/

相关文章:

jQuery 双动画焦点?

javascript - 在 beforeunload 事件上查询数据库

jQuery 从 div 检索数据

JavaScript Keycode 46 是 DEL 功能键还是 (.) 句号?

javascript - WebStorm 11 - Unresolved 方法

jquery - 使用列 View ext 时是否可以设置 fancyTree 的高度

javascript - 使用ajax从php和mysql获取数据

php - 推荐一个好的图片上传和裁剪工具

javascript - 通过 SelectBox 的下一个上一个按钮

javascript - 如何使用 javascript/jquery 来防止将小数点输入到 HTML 文本字段中?