Jquery 如果单选按钮被选中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6654601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:11:08  来源:igfitidea点击:

Jquery If radio button is checked

jqueryhtmlradio-button

提问by Daniel H

Possible Duplicate:
Check of specific radio button is checked

可能的重复:
检查特定单选按钮

I have these 2 radio buttons at the moment so that the user can decide whether they need postage included in the price or not:

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

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

I need to use Jquery to check if the 'yes' radio button is checked, and if it is, do an append function. Could someone tell me how I'd do this please?

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

Thanks for any help

谢谢你的帮助

edit:

编辑:

I've updated my code to this, but it's not working. Am I doing something wrong?

我已经将我的代码更新为这个,但它不起作用。难道我做错了什么?

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

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

});

// ]]>
</script>

回答by David says reinstate Monica

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

Or, the above - again - using a little lesssuperfluous jQuery:

或者,以上 - 再次 - 使用不那么多余的 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
        }
    });

Revised (improved-some) jQuery:

修订(改进一些)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小提琴演示

And, further, a mild update (since I was editing to include Snippets as well as the JS Fiddle links), in order to wrap the <input />elements with <label>s - allow for clicking the text to update the relevant <input />- and changing the means of creating the content to append:

此外,还有一个温和的更新(因为我正在编辑以包括代码段和 JS Fiddle 链接),以便<input /><label>s包裹元素- 允许单击文本以更新相关内容<input />- 并更改创建追加内容:

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.

JS小提琴演示

Also, if you only need to show content depending on which element is checked by the user, a slight update that will toggle visibility using an explicit show/hide:

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

// 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>

And, finally, using just CSS:

最后,只使用 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.

JS小提琴演示

References:

参考:

回答by ShankarSangoli

Try this

尝试这个

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

回答by Mrchief

Something like this:

像这样的东西:

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

回答by Shef

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

This will listen for a change event on the radio buttons. At the time the user clicks Yes, the event will fire and you will be able to append anything you like to the DOM.

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

回答by Phil

if($('#test2').is(':checked')) {
    $(this).append('stuff');
} 

回答by genesis

$("input").bind('click', function(e){
   if ($(this).val() == 'Yes') {
        $("body").append('whatever');
   }
});

回答by Justin Ethier

Try this:

尝试这个:

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

回答by Benjamin

jQuery('input[name="inputName"]:checked').val()

回答by M.S Shohan

This will listen to the changed event. I have tried the answers from others but those did not work for me and finally, this one worked.

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

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