简体   繁体   English

如何使用 jQuery 检查单选按钮?

[英]How to check a radio button with jQuery?

I try to check a radio button with jQuery.我尝试使用 jQuery 检查单选按钮。 Here's my code:这是我的代码:

<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>

For versions of jQuery equal or above (>=) 1.6, use:对于等于或高于 (>=) 1.6 的 jQuery 版本,请使用:

$("#radio_1").prop("checked", true);

For versions prior to (<) 1.6, use:对于 (<) 1.6 之前的版本,请使用:

$("#radio_1").attr('checked', 'checked');

Tip: You may also want to call click() or change() on the radio button afterwards.提示:之后您可能还想在单选按钮上调用click()change() See comments for more info.有关更多信息,请参阅评论。

Try this.尝试这个。

In this example, I'm targeting it with its input name and value在这个例子中,我用它的输入名称和值来定位它

$("input[name=background][value='some value']").prop("checked",true);

Good to know: in case of multi-word value, it will work because of apostrophes, too.很高兴知道:在多字值的情况下,它也会因为撇号而起作用。

在 jQuery 1.6 中添加的另一个函数 prop() 用于相同的目的。

$("#radio_1").prop("checked", true); 

Short and easy to read option:简短易读的选项:

$("#radio_1").is(":checked")

It returns true or false, so you can use it in "if" statement.它返回 true 或 false,因此您可以在“if”语句中使用它。

Try this.尝试这个。

To check Radio button using Value use this.要使用检查单选按钮,请使用它。

$('input[name=type][value=2]').attr('checked', true); 

Or或者

$('input[name=type][value=2]').attr('checked', 'checked');

Or或者

$('input[name=type][value=2]').prop('checked', 'checked');

To check Radio button using ID use this.要使用ID检查单选按钮,请使用它。

$('#radio_1').attr('checked','checked');

Or或者

$('#radio_1').prop('checked','checked');

Try This:尝试这个:

$("input[name=type]").val(['1']);

http://jsfiddle.net/nwo706xw/ http://jsfiddle.net/nwo706xw/

The $.prop way is better: $.prop方式更好:

$(document).ready(function () {                            
    $("#radio_1").prop('checked', true);        
});

and you can test it like the following:你可以像下面这样测试它:

$(document).ready(function () {                            
    $("#radio_1, #radio_2", "#radio_3").change(function () {
        if ($("#radio_1").is(":checked")) {
            $('#div1').show();
        }
        else if ($("#radio_2").is(":checked")) {
            $('#div2').show();
        }
        else 
            $('#div3').show();
    });        
});

Use prop() mehtod使用prop()方法

在此处输入图片说明

Source Link链接

<p>
    <h5>Radio Selection</h5>

    <label>
        <input type="radio" name="myRadio" value="1"> Option 1
    </label>
    <label>
        <input type="radio" name="myRadio" value="2"> Option 2
    </label>
    <label>
        <input type="radio" name="myRadio" value="3"> Option 3
    </label>
</p>

<p>
    <button>Check Radio Option 2</button>
</p>


<script>
    $(function () {

        $("button").click(function () {
            $("input:radio[value='2']").prop('checked',true);
        });

    });
</script>

Surprisingly, the most popular and accepted answer ignores triggering appropriate event despite of the comments.令人惊讶的是,尽管有评论,但最受欢迎和接受的答案却忽略了触发适当的事件。 Make sure you invoke .change() , otherwise all the "on change" bindings will ignore this event.确保调用.change() ,否则所有“on change”绑定都将忽略此事件。

$("#radio_1").prop("checked", true).change();

You have to do你必须要做

jQuery("#radio_1").attr('checked', 'checked');

That's the HTML attribute那是 HTML 属性

If property name does not work don't forget that id still exists.如果属性name不起作用,请不要忘记id仍然存在。 This answer is for people who wants to target the id here how you do.这个答案适用于想要在此处定位id人。

$('input[id=element_id][value=element_value]').prop("checked",true);

Because property name does not work for me.因为属性name对我不起作用。 Make sure you don't surround id and name with double/single quotations.确保不要用双引号/单引号将idname括起来。

Cheers!干杯!

我们应该告诉它是一个radio按钮。所以请尝试使用以下代码。

$("input[type='radio'][name='userRadionButtonName']").prop('checked', true);

是的,它对我来说就像这样:

$("#radio_1").attr('checked', 'checked');

Try this尝试这个

$(document).ready(function(){
    $("input[name='type']:radio").change(function(){
        if($(this).val() == '1')
        {
          // do something
        }
        else if($(this).val() == '2')
        {
          // do something
        }
        else if($(this).val() == '3')
        {
          // do something
        }
    });
});
$("input[name=inputname]:radio").click(function() {
    if($(this).attr("value")=="yes") {
        $(".inputclassname").show();
    }
    if($(this).attr("value")=="no") {
        $(".inputclassname").hide();
    }
});

Get value:获取价值:

$("[name='type'][checked]").attr("value");

Set value:设定值:

$(this).attr({"checked":true}).prop({"checked":true});

Radio Button click add attr checked:选中单选按钮单击添加属性:

$("[name='type']").click(function(){
  $("[name='type']").removeAttr("checked");
  $(this).attr({"checked":true}).prop({"checked":true});
});

Try this with example用例子试试这个

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="radio" name="radio" value="first"/> 1 <br/>
<input type="radio" name="radio" value="second"/> 2 <br/>
</form>


<script>
$(document).ready(function () {
    $('#myForm').on('click', function () {
        var value = $("[name=radio]:checked").val();

        alert(value);
    })
});
</script>

Just in case anyone is trying to achieve this while using jQuery UI, you will also need to refresh the UI checkbox object to reflect the updated value:以防万一有人在使用 jQuery UI 时试图实现这一点,您还需要刷新 UI 复选框对象以反映更新后的值:

$("#option2").prop("checked", true); // Check id option2
$("input[name='radio_options']").button("refresh"); // Refresh button set

I use this code:我使用这个代码:

I'm sorry for English.我为英语感到抱歉。

 var $j = jQuery.noConflict(); $j(function() { // add handler $j('#radio-1, #radio-2').click(function(){ // find all checked and cancel checked $j('input:radio:checked').prop('checked', false); // this radio add cheked $j(this).prop('checked', true); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <fieldset class="section"> <legend>Radio buttons</legend> <label> <input type="radio" id="radio-1" checked> Option one is this and that&mdash;be sure to include why it's great </label> <br> <label> <input type="radio" id="radio-2"> Option two can be something else </label> </fieldset>

尝试这个

var isChecked = $("#radio_1")[0].checked;
function rbcitiSelction(e) {
     debugger
    $('#trpersonalemail').hide();
    $('#trcitiemail').show();
}

function rbpersSelction(e) {
    var personalEmail = $(e).val();
    $('#trpersonalemail').show();
    $('#trcitiemail').hide();
}

$(function() {  
    $("#citiEmail").prop("checked", true)
});

I got some related example to be enhanced, how about if I want to add a new condition, lets say, if I want colour scheme to be hidden after I click on project Status value except Pavers and Paving Slabs.我得到了一些相关的例子来增强,如果我想添加一个新条件,比如说,如果我想在我点击项目状态值后隐藏配色方案,除了摊铺机和铺路板。

Example is in here:示例在这里:

$(function () {
    $('#CostAnalysis input[type=radio]').click(function () {
        var value = $(this).val();

        if (value == "Supply & Lay") {
            $('#ul-suplay').empty();
            $('#ul-suplay').append('<fieldset data-role="controlgroup"> \

http://jsfiddle.net/m7hg2p94/4/ http://jsfiddle.net/m7hg2p94/4/

I've just have a similar problem, a simple solution is to just use:我刚刚遇到了类似的问题,一个简单的解决方案是使用:

.click()

Any other solution will work if you refresh radio after calling function.如果您在调用函数后刷新收音机,任何其他解决方案都将起作用。

In addition, you can check if the element is checked or not:此外,您可以检查元素是否被选中:

if ($('.myCheckbox').attr('checked'))
{
   //do others stuff
}
else
{
   //do others stuff
}

You can checked for unchecked element:您可以检查未检查的元素:

$('.myCheckbox').attr('checked',true) //Standards way

You can also uncheck this way:您也可以通过这种方式取消选中:

$('.myCheckbox').removeAttr('checked')

You can checked for radio button:您可以检查单选按钮:

For versions of jQuery equal or above (>=) 1.6, use:对于等于或高于 (>=) 1.6 的 jQuery 版本,请使用:

$("#radio_1").prop("checked", true);

For versions prior to (<) 1.6, use:对于 (<) 1.6 之前的版本,请使用:

$("#radio_1").attr('checked', 'checked');
$("#radio_1").attr('checked', true);
//or
$("#radio_1").attr('checked', 'checked');

I used jquery-1.11.3.js我使用了jquery-1.11.3.js

Basic Enable & disable基本启用和禁用

Tips 1: (Radio button type common Disable & Enable) Tips 1:(单选按钮类型常见的禁用和启用)

$("input[type=radio]").attr('disabled', false);
$("input[type=radio]").attr('disabled', true); 

Tips 2: ( ID selector Using prop() or attr()) Tips 2:( ID选择器使用prop()或attr())

$("#paytmradio").prop("checked", true);
$("#sbiradio").prop("checked", false);

jQuery("#paytmradio").attr('checked', 'checked'); // or true this won't work
jQuery("#sbiradio").attr('checked', false);

Tips 3: ( Class selector Using prop() or arrt()) Tips 3:( Class selector Using prop() or arrt())

$(".paytm").prop("checked", true);
$(".sbi").prop("checked", false);

jQuery(".paytm").attr('checked', 'checked'); // or true
jQuery(".sbi").attr('checked', false);

OTHER TIPS其他提示

$("#paytmradio").is(":checked")   // Checking is checked or not
$(':radio:not(:checked)').attr('disabled', true); // All not check radio button disabled

$('input[name=payment_type][value=1]').attr('checked', 'checked'); //input type via checked
 $("input:checked", "#paytmradio").val() // get the checked value

index.html索引.html

<div class="col-md-6">      
    <label class="control-label" for="paymenttype">Payment Type <span style="color:red">*</span></label>
    <div id="paymenttype" class="form-group" style="padding-top: inherit;">
        <label class="radio-inline" class="form-control"><input  type="radio" id="paytmradio"  class="paytm" name="paymenttype" value="1" onclick="document.getElementById('paymentFrm').action='paytmTest.php';">PayTM</label>
        <label class="radio-inline" class="form-control"><input  type="radio" id="sbiradio" class="sbi" name="paymenttype" value="2" onclick="document.getElementById('paymentFrm').action='sbiTest.php';">SBI ePAY</label>
    </div>
</div>

This answer is thanks to Paul LeBeau in a comment .这个答案要感谢 Paul LeBeau 在评论中 I thought I'd write it up as a proper answer since there surprisingly wasn't one.我想我会把它写成一个正确的答案,因为令人惊讶的是没有一个。

The only thing that worked for me (jQuery 1.12.4, Chrome 86) was:唯一对我有用的东西(jQuery 1.12.4,Chrome 86)是:

$(".js-my-radio-button").trigger("click");

This does everything I want – changes which radio button looks selected (both visually and programmatically) and triggers events such as change on the radio button.这完成了我想要的一切 - 更改哪个单选按钮看起来被选中(视觉和编程)并触发事件,例如单选按钮上的change

Just setting the "checked" attribute as other answers suggest would not change which radio button was selected for me.只是按照其他答案的建议设置“已检查”属性不会更改为我选择的单选按钮。

try this尝试这个

 $("input:checked", "#radioButton").val()

if checked returns True if not checked returns False如果选中返回True如果未选中返回False

jQuery v1.10.1

Try This:尝试这个:

$(document).ready(function(){
  $("#Id").prop("checked", true).checkboxradio('refresh');
});

Some times above solutions do not work, then you can try below:有时上述解决方案不起作用,那么您可以尝试以下方法:

jQuery.uniform.update(jQuery("#yourElementID").attr('checked',true));
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',false));

Another way you can try is:您可以尝试的另一种方法是:

jQuery("input:radio[name=yourElementName]:nth(0)").attr('checked',true);

I try to check a radio button with jQuery.我尝试使用jQuery检查单选按钮。 Here's my code:这是我的代码:

<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>

And the JavaScript:和JavaScript:

jQuery("#radio_1").attr('checked', true);

Doesn't work:不起作用:

jQuery("input[value='1']").attr('checked', true);

Doesn't work:不起作用:

jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);

Doesn't work:不起作用:

Do you have another idea?你还有其他主意吗? What am I missing?我想念什么?

In case you don't want to include a big library like jQuery for something this simple, here's an alternative solution using built-in DOM methods: 如果您不希望像jQuery这样的大型库包含这么简单的东西,这里是使用内置DOM方法的替代解决方案:

 // Check checkbox by id: document.querySelector('#radio_1').checked = true; // Check checkbox by value: document.querySelector('#type > [value="1"]').checked = true; // If this is the only input with a value of 1 on the page, you can leave out the #type > document.querySelector('[value="1"]').checked = true; 
 <form> <div id='type'> <input type='radio' id='radio_1' name='type' value='1' /> <input type='radio' id='radio_2' name='type' value='2' /> <input type='radio' id='radio_3' name='type' value='3' /> </div> </form> 

Shortest最短的<\/h1>
radio_1.checked<\/code> <\/pre>

 checkBtn.onclick = e=> { console.log( radio_1.checked ); }<\/code><\/pre>
 Select first radio and click button <!-- Question html --> <form> <div id='type'> <input type='radio' id='radio_1' name='type' value='1' \/> <input type='radio' id='radio_2' name='type' value='2' \/> <input type='radio' id='radio_3' name='type' value='3' \/> 
<\/form> <!-- Test html --> <button id="checkBtn">Check<\/button><\/code><\/pre>

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM