首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用jQuery/JavaScript来找出单选按钮何时不被选中?

如何使用jQuery/JavaScript来找出单选按钮何时不被选中?
EN

Stack Overflow用户
提问于 2014-02-11 09:24:39
回答 3查看 921关注 0票数 8

当选中复选框时,我试图使用jquery函数隐藏/显示某些表单元素。在选中单选按钮时,也应该使用相同的函数来隐藏/显示表单元素。问题是单选按钮。我的函数无法判断单选按钮何时不被选中,因此当选中它时变得可见的div现在可以被隐藏,因为它是未选中的。我展示了下面的代码:

代码语言:javascript
运行
复制
<!-- html on one of the pages -->
<fieldset>
  <label for="viaMail">Send offers to my mail</label>
  <input type="checkbox" id="viaMail" class="slide" autocomplete="off">

  <label for="viaEmail">Send offers to my email address</label>
  <input type="checkbox" id="viaEmail" autocomplete="off">

</fieldset>

<div class="viaMail">  <!-- div hidden with css using display: none rule -->
   <!-- input fields for mailing addresses etc --> 
</div>
<!-- end page one html -->

<!-- html on page two -->   
<fieldset>
  <label for="viaMail">Send offers to my mail</label>
  <input type="radio" name="group1" id="viaMail" class="slide" autocomplete="off">

  <label for="viaEmail">Send offers to my email address</label>
  <input type="radio" name="group1" id="viaEmail" autocomplete="off">

</fieldset>

<div class="viaMail">  <!-- div hidden with css using display: none rule -->
   <!-- input fields for mailing addresses etc -->
</div>
代码语言:javascript
运行
复制
/* the js function */

ShowHideDiv={
init:function(){
    var radcheck = $(".slide");

//if the input element has the class 'slide' then the value of it's 'id' attribute 
//is retrieved and the class which has the same name as the 'id' of the current input
//element is hidden or slided into view - in this case the 'viaMail' class

    radcheck.on("change",function(){
        if($(this).prop('checked')== true) {
            $('body').find("."+$(this).attr('id')).slideDown('slow');
        }
        else {
            $('body').find("."+$(this).attr('id')).slideUp('fast');
        }
    });

}
  }

我已经为复选框尝试了这个函数,它运行得很好。它不工作的单选按钮- div是‘滑下’进入视图,但它不会消失'slideUp‘时,另一个单选按钮被选中。会很感激你的帮助。

EN

回答 3

Stack Overflow用户

发布于 2014-02-11 09:26:20

应该如下所示

代码语言:javascript
运行
复制
if( $(this).prop('checked', true) )
票数 3
EN

Stack Overflow用户

发布于 2014-02-11 09:28:13

您可以使用.is()来检查类似的内容。

代码语言:javascript
运行
复制
if( $(this).is(':checked') )

文档中会有更多关于这一点的报道。

此外,您还可以将$('body').find("."+$(this).attr('id'))替换为只使用$("." + $(this).attr('id'))

Demo 这里

代码语言:javascript
运行
复制
$(function () {
    $('.slide').on("change", function () {
        if ($(this).is(':checked')) {
            $("." + $(this).attr('id')).slideDown('slow');
        } else {
            $("." + $(this).attr('id')).slideUp('fast');
        }
    });
});
票数 3
EN

Stack Overflow用户

发布于 2014-02-11 09:28:43

代码语言:javascript
运行
复制
if( !$(this).is(':checked') ) // if its unchecked
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21697764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档