Html 如何获取所选单选按钮的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15839169/
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-29 07:14:40  来源:igfitidea点击:

How to get value of selected radio button?

javascripthtmlradio-button

提问by ZombieBatman

I want to get the selected value from a group of radio buttons.

我想从一组单选按钮中获取选定的值。

Here's my HTML:

这是我的 HTML:

<div id="rates">
  <input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
  <input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
  <input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate  
</div>

Here's my .js:

这是我的 .js:

var rates = document.getElementById('rates').value;
var rate_value;
if(rates =='Fixed Rate'){
    rate_value = document.getElementById('r1').value;

}else if(rates =='Variable Rate'){
    rate_value = document.getElementById('r2').value;

}else if(rates =='Multi Rate'){
    rate_value = document.getElementById('r3').value;
}  

document.getElementById('results').innerHTML = rate_value;

I keep getting undefined.

我不断变得不确定。

采纳答案by Joe F

var rates = document.getElementById('rates').value;

The rates element is a div, so it won't have a value. This is probably where the undefinedis coming from.

rate 元素是 a div,因此它没有值。这可能就是它的undefined来源。

The checkedproperty will tell you whether the element is selected:

checked属性将告诉您该元素是否被选中:

if (document.getElementById('r1').checked) {
  rate_value = document.getElementById('r1').value;
}

回答by Parthik Gosar

This works in IE9 and above and all other browsers.

这适用于 IE9 及更高版本以及所有其他浏览器。

document.querySelector('input[name="rate"]:checked').value;

回答by Joe

You can get the value by using the checkedproperty.

您可以通过使用该checked属性来获取该值。

var rates = document.getElementsByName('rate');
var rate_value;
for(var i = 0; i < rates.length; i++){
    if(rates[i].checked){
        rate_value = rates[i].value;
    }
}

回答by Daniel

For you people living on the edge:

对于生活在边缘的人们:

There is now something called a RadioNodeListand accessing it's value property will return the value of the currently checked input. This will remove the necessity of first filtering out the 'checked' input as we see in many of the posted answers.

现在有一个叫做RadioNodeList 的东西,访问它的 value 属性将返回当前检查输入的值。这将消除我们在许多已发布的答案中看到的首先过滤掉“已检查”输入的必要性。

Example Form

示例表格

<form id="test">
<label><input type="radio" name="test" value="A"> A</label>
<label><input type="radio" name="test" value="B" checked> B</label>
<label><input type="radio" name="test" value="C"> C</label>
</form>

To retrieve the checked value, you could do something like this:

要检索选中的值,您可以执行以下操作:

var form = document.getElementById("test");
alert(form.elements["test"].value);

The JSFiddle to prove it: http://jsfiddle.net/vjop5xtq/

证明它的 JSFiddle:http: //jsfiddle.net/vjop5xtq/

Please note this was implemented in Firefox 33 (All other major browser seems to support it). Older browsers will require a polfyill for RadioNodeListfor this to properly function

请注意这是在 Firefox 33 中实现的(所有其他主要浏览器似乎都支持它)。较旧的浏览器将需要 polfyillRadioNodeList才能正常运行

回答by Malathy

The one worked for me is given below from api.jquery.com.

下面从 api.jquery.com 给出了对我有用的那个。

HTML

HTML

<input type="radio" name="option" value="o1">option1</input>
<input type="radio" name="option" value="o2">option2</input>

JavaScript

JavaScript

var selectedOption = $("input:radio[name=option]:checked").val()

The variable selectedOption will contain the value of the selected radio button (i.e) o1 or o2

变量 selectedOption 将包含所选单选按钮的值(即)o1 或 o2

回答by JHS

Another (apparently older) option is to use the format: "document.nameOfTheForm.nameOfTheInput.value;" e.g. document.mainForm.rads.value;

另一个(显然较旧的)选项是使用以下格式:“document.nameOfTheForm.nameOfTheInput.value;” 例如document.mainForm.rads.value;

document.mainForm.onclick = function(){
    var radVal = document.mainForm.rads.value;
    result.innerHTML = 'You selected: '+radVal;
}
<form id="mainForm" name="mainForm">
    <input type="radio" name="rads" value="1" />
    <input type="radio" name="rads" value="2" />
    <input type="radio" name="rads" value="3" />
    <input type="radio" name="rads" value="4" />
</form>
<span id="result"></span>

You can refer to the element by its name within a form. Your original HTML does not contain a form element though.

您可以在表单中通过名称引用元素。但是,您的原始 HTML 不包含表单元素。

Fiddle here (works in Chrome and Firefox): https://jsfiddle.net/Josh_Shields/23kg3tf4/1/

在这里小提琴(适用于 Chrome 和 Firefox):https: //jsfiddle.net/Josh_Shields/23kg3tf4/1/

回答by pawan vedak

Use document.querySelector('input[type = radio]:checked').value;to get value of selected checkbox , you can use other attributes to get value like name = genderetc. please go through below snippet definitely it will helpful to you,

使用document.querySelector('input[type = radio]:checked').value; 要获取选定复选框的值,您可以使用其他属性来获取值,如名称 = 性别等。请仔细阅读下面的代码片段,它肯定会对您有所帮助,

Solution

解决方案

document.mainForm.onclick = function(){
    var gender = document.querySelector('input[name = gender]:checked').value;
    result.innerHTML = 'You Gender: '+gender;
}
<form id="mainForm" name="mainForm">
    <input type="radio" name="gender" value="Male" checked/>Male
    <input type="radio" name="gender" value="Female" />Female
    <input type="radio" name="gender" value="Others" />Others
</form>
<span id="result"></span>

Thank-You

谢谢你

回答by pawan vedak

HTML CODE:

HTML代码:

<input type="radio" name="rdoName" value="YES"/> <input type="radio" name="rdoName" value="NO"/>

<input type="radio" name="rdoName" value="YES"/> <input type="radio" name="rdoName" value="NO"/>

JQUERY CODE:

查询代码:

var value= $("input:radio[name=rdoName]:checked").val();

$("#btnSubmit").click(function(){
var value=$("input:radio[name=rdoName]:checked").val();
console.log(value);
alert(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="rdoName" value="YES"/> YES
<input type="radio" name="rdoName" value="NO"/> NO
<br/>
<input type="button"id="btnSubmit"value="Which one Selected"/>

You will get

你会得到

value="YES" //if checked Radio Button with the value "YES"
value="NO" //if checked Radio Button with the value "NO"

回答by Frank Conijn

A year or so has passed since the question was asked, but I thought a substantial improvement of the answers was possible. I find this the easiest and most versatile script, because it checks whether a button has been checked, and if so, what its value is:

自从提出这个问题以来已经过去了一年左右,但我认为答案的实质性改进是可能的。我发现这是最简单和最通用的脚本,因为它检查按钮是否已被选中,如果是,它的值是什么:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Check radio checked and its value</title>
</head>
<body>

    <form name="theFormName">
        <input type="radio" name="theRadioGroupName" value="10">
        <input type="radio" name="theRadioGroupName" value="20">
        <input type="radio" name="theRadioGroupName" value="30">
        <input type="radio" name="theRadioGroupName" value="40">
        <input type="button" value="Check" onclick="getRadioValue('theRadioGroupName')">
    </form>

    <script>
        function getRadioValue(groupName) {
            var radios = theFormName.elements[groupName];
            window.rdValue; // declares the global variable 'rdValue'
            for (var i=0; i<radios.length; i++) {
                var someRadio = radios[i];
                if (someRadio.checked) {
                    rdValue = someRadio.value;
                    break;
                }
                else rdValue = 'noRadioChecked';
            }
            if (rdValue == '10') {
                alert('10'); // or: console.log('10')
            }
            else if (rdValue == 'noRadioChecked') {
                alert('no radio checked');
            }
        }
    </script>
</body>
</html>

You can also call the function within another function, like this:

您还可以在另一个函数中调用该函数,如下所示:

function doSomething() {
    getRadioValue('theRadioGroupName');
    if (rdValue == '10') {
        // do something
    }
    else if (rdValue == 'noRadioChecked') {
        // do something else
    }  
} 

回答by pradeep

In Javascript we can get the values by using Id's "getElementById()" in the above code you posted has contain name not Id so you to modify like this

在Javascript中,我们可以通过使用Id的“ getElementById()”来获取值,您发布的上述代码包含名称而不是Id,因此您可以像这样修改

if (document.getElementById('r1').checked) {
  rate_value = document.getElementById('r1').value;
}

use this rate_value according to your code

根据您的代码使用此 rate_value