【问题标题】:Jquery If radio button is checkedJquery如果选中单选按钮
【发布时间】:2011-10-03 00:47:53
【问题描述】:

可能重复:
Check of specific radio button is checked

我现在有这两个单选按钮,以便用户可以决定他们是否需要在价格中包含邮资:

<input type="radio" id="postageyes" name="postage" value="Yes" /> Yes
<input type="radio" id="postageno" name="postage" value="No" /> No

我需要使用 Jquery 来检查是否选中了“是”单选按钮,如果是,请执行附加功能。有人可以告诉我该怎么做吗?

感谢您的帮助

编辑:

我已将我的代码更新为此,但它不起作用。我做错了吗?

<script type='text/javascript'>
// <![CDATA[
jQuery(document).ready(function(){

$('input:radio[name="postage"]').change(function(){
    if($(this).val() == 'Yes'){
       alert("test");
    }
});

});

// ]]>
</script>

【问题讨论】:

  • @Daniel H:关于你的更新:it's working just fine!
  • 这很奇怪,它只是无法在我的网站上运行。至少我知道代码是对的,我会试着找出它有什么问题,感谢所有的答案!

标签: jquery html radio-button


【解决方案1】:
$('input:radio[name="postage"]').change(
    function(){
        if ($(this).is(':checked') && $(this).val() == 'Yes') {
            // append goes here
        }
    });

或者,以上 - 再次 - 使用一点 less 多余的 jQuery:

$('input:radio[name="postage"]').change(
    function(){
        if (this.checked && this.value == 'Yes') {
            // note that, as per comments, the 'changed'
            // <input> will *always* be checked, as the change
            // event only fires on checking an <input>, not
            // on un-checking it.
            // append goes here
        }
    });

修改(改进了一些)jQuery:

// defines a div element with the text "You're appendin'!"
// assigns that div to the variable 'appended'
var appended = $('<div />').text("You're appendin'!");

// assigns the 'id' of "appended" to the 'appended' element
appended.id = 'appended';

// 1. selects '<input type="radio" />' elements with the 'name' attribute of 'postage'
// 2. assigns the onChange/onchange event handler
$('input:radio[name="postage"]').change(
    function(){

        // checks that the clicked radio button is the one of value 'Yes'
        // the value of the element is the one that's checked (as noted by @shef in comments)
        if ($(this).val() == 'Yes') {

            // appends the 'appended' element to the 'body' tag
            $(appended).appendTo('body');
        }
        else {

            // if it's the 'No' button removes the 'appended' element.
            $(appended).remove();
        }
    });

var appended = $('<div />').text("You're appendin'!");
appended.id = 'appended';
$('input:radio[name="postage"]').change(function() {
  if ($(this).val() == 'Yes') {
    $(appended).appendTo('body');
  } else {
    $(appended).remove();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<input type="radio" id="postageyes" name="postage" value="Yes" />Yes
<input type="radio" id="postageno" name="postage" value="No" />No

JS Fiddle demo.

此外,还有一个温和的更新(因为我正在编辑以包括片段以及 JS Fiddle 链接),以便用 &lt;label&gt;s 包装 &lt;input /&gt; 元素 - 允许单击文本以更新相关&lt;input /&gt; - 并更改创建要附加的内容的方式:

var appended = $('<div />', {
  'id': 'appended',
  'text': 'Appended content'
});
$('input:radio[name="postage"]').change(function() {
  if ($(this).val() == 'Yes') {
    $(appended).appendTo('body');
  } else {
    $(appended).remove();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="radio" id="postageyes" name="postage" value="Yes" />Yes</label>
<label>
  <input type="radio" id="postageno" name="postage" value="No" />No</label>

JS Fiddle demo.

此外,如果您只需要根据用户检查的元素来显示内容,则可以稍微更新一下,使用显式显示/隐藏来切换可见性:

// caching a reference to the dependant/conditional content:
var conditionalContent = $('#conditional'),
    // caching a reference to the group of inputs, since we're using that
    // same group twice:
    group = $('input[type=radio][name=postage]');

// binding the change event-handler:
group.change(function() {
  // toggling the visibility of the conditionalContent, which will
  // be shown if the assessment returns true and hidden otherwise:
  conditionalContent.toggle(group.filter(':checked').val() === 'Yes');
  // triggering the change event on the group, to appropriately show/hide
  // the conditionalContent on page-load/DOM-ready:
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="radio" id="postageyes" name="postage" value="Yes" />Yes</label>
<label>
  <input type="radio" id="postageno" name="postage" value="No" />No</label>
<div id="conditional">
  <p>This should only show when the 'Yes' radio &lt;input&gt; element is checked.</p>
</div>

最后,只使用 CSS:

/* setting the default of the conditionally-displayed content
to hidden: */
#conditional {
  display: none;
}

/* if the #postageyes element is checked then the general sibling of
that element, with the id of 'conditional', will be shown: */
#postageyes:checked ~ #conditional {
  display: block;
}
<!-- note that the <input> elements are now not wrapped in the <label> elements,
in order that the #conditional element is a (subsequent) sibling of the radio
<input> elements: -->
<input type="radio" id="postageyes" name="postage" value="Yes" />
<label for="postageyes">Yes</label>
<input type="radio" id="postageno" name="postage" value="No" />
<label for="postageno">No</label>
<div id="conditional">
  <p>This should only show when the 'Yes' radio &lt;input&gt; element is checked.</p>
</div>

JS Fiddle demo.

参考资料:

【讨论】:

  • 不用看有没有勾选。否则它永远不会有价值。浪费资源!
【解决方案2】:

试试这个

if($("input:radio[name=postage]").is(":checked")){
  //Code to append goes here
}

【讨论】:

    【解决方案3】:

    类似这样的:

    if($('#postageyes').is(':checked')) {
    // do stuff
    }
    

    【讨论】:

    • jQuery 对象总是真实的。您可能想改用$(...).length
    • 您的意思是#postageyes:checked$('#postageyes').is(':checked')
    • @pimvdb 根据jQuery docs, is() 返回一个布尔值。所以调用.length() 是坏的。来自文档:“与其他过滤方法不同,.is() 不会创建新的 jQuery 对象。相反,它允许您在不修改的情况下测试 jQuery 对象的内容。” -- api.jquery.com/is
    【解决方案4】:
    if($('#test2').is(':checked')) {
        $(this).append('stuff');
    } 
    

    【讨论】:

      【解决方案5】:
      $('input:radio[name="postage"]').change(function(){
          if($(this).val() === 'Yes'){
             // append stuff
          }
      });
      

      这将侦听单选按钮上的更改事件。当用户点击 Yes 时,该事件将触发,您将能够将任何您喜欢的内容附加到 DOM。

      【讨论】:

        【解决方案6】:
        $("input").bind('click', function(e){
           if ($(this).val() == 'Yes') {
                $("body").append('whatever');
           }
        });
        

        【讨论】:

        • 对此不太确定,但是$("#postageyes:checked" 不会总是返回 true 吗?您不必使用.length 来让它工作吗?
        • 删除了“或”以及之后的所有内容
        【解决方案7】:

        试试这个:

        if ( jQuery('#postageyes').is(':checked') ){ ... }
        

        【讨论】:

          【解决方案8】:

          这将监听更改的事件。我已经尝试了其他人的答案,但那些对我不起作用,最后,这个起作用了。

          $('input:radio[name="postage"]').change(function(){
              if($(this).is(":checked")){
                  alert("lksdahflk");
              }
          });
          

          【讨论】:

            【解决方案9】:
            jQuery('input[name="inputName"]:checked').val()
            

            【讨论】:

            • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
            • 知道了。下一个答案会有一个。
            猜你喜欢
            • 2011-12-19
            • 2017-10-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-10-27
            • 2011-08-21
            相关资源
            最近更新 更多