为电台组中的所选电台设置一个值 [英] Set selected radio from radio group with a value

查看:72
本文介绍了为电台组中的所选电台设置一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为什么要为此苦苦挣扎?

Why am I struggling with this?

我有一个值:5

如何检查值为"5"的"mygroup"组的单选按钮?

How do I check the radio button of group "mygroup" with the value of 5?

$("input[name=mygroup]").val(5); // doesn't work?

推荐答案

借助属性选择器,您可以选择具有相应值的输入元素.然后,您必须使用 .attr :

With the help of the attribute selector you can select the input element with the corresponding value. Then you have to set the attribute explicitly, using .attr:

var value = 5;
$("input[name=mygroup][value=" + value + "]").attr('checked', 'checked');

从jQuery 1.6开始,您还可以将 .prop 方法与布尔值一起使用(此方法应该是首选方法):

Since jQuery 1.6, you can also use the .prop method with a boolean value (this should be the preferred method):

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

请记住,您首先只需要从一个单选按钮组下的任何一个单选按钮中删除选中的属性,然后您便可以将选中的属性/属性添加到该单选按钮组中的一个单选按钮中.

Remember you first need to remove checked attribute from any of radio buttons under one radio buttons group only then you will be able to add checked property / attribute to one of the radio button in that radio buttons group.

要从一个单选按钮组的所有单选按钮中删除选中属性的代码-

Code To Remove Checked Attribute from all radio buttons of one radio button group -

$('[name="radioSelectionName"]').removeAttr('checked');

这篇关于为电台组中的所选电台设置一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆