简体   繁体   English

如何获取选定单选按钮的值?

[英]How to get value of selected radio button?

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.我一直不确定。

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

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

The rates element is a div , so it won't have a value. rate 元素是一个div ,因此它没有值。 This is probably where the undefined is coming from.这可能是undefined的来源。

The checked property will tell you whether the element is selected: checked属性会告诉你元素是否被选中:

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

Or或者

$("input[type='radio'][name='rate']:checked").val();

您可以使用checked<\/code>属性获取值。

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;
    }
}

For you people living on the edge:对于生活在边缘的人们:

There is now something called a RadioNodeList and accessing it's value property will return the value of the currently checked input.现在有一个叫做RadioNodeList 的东西,访问它的 value 属性将返回当前检查的输入的值。 This will remove the necessity of first filtering out the 'checked' input as we see in many of the posted answers.正如我们在许多发布的答案中看到的那样,这将消除首先过滤掉“已检查”输入的必要性。

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).请注意,这是在 Firefox 33 中实现的(所有其他主要浏览器似乎都支持它)。 Older browsers will require a polfyill for RadioNodeList for this to properly function较旧的浏览器需要 RadioNodeList 的RadioNodeList才能正常运行

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 (ie) o1 or o2变量 selectedOption 将包含所选单选按钮的值(即)o1 或 o2

Another (apparently older) option is to use the format: "document.nameOfTheForm.nameOfTheInput.value;"另一个(显然较旧)选项是使用格式:“document.nameOfTheForm.nameOfTheInput.value;” eg document.mainForm.rads.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/

Use document.querySelector('input[type = radio]:checked').value;使用document.querySelector('input[type = radio]:checked').value; to get value of selected checkbox , you can use other attributes to get value like name = gender etc. please go through below snippet definitely it will helpful to you,要获取选定复选框的值,您可以使用其他属性来获取值,例如名称 = 性别等。请仔细阅读下面的代码段,这肯定会对您有所帮助,

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

HTML CODE: HTML 代码:

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

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

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

Assuming your form element is referred to by myForm variable below, and that your radio buttons share the name "my-radio-button-group-name", the following is pure JavaScript and standards compliant (although I have not checked it to be available everywhere):假设您的表单元素由下面的myForm变量引用,并且您的单选按钮共享名称“my-radio-button-group-name”,以下是纯 JavaScript 和标准兼容(尽管我没有检查它是否可用到处):

myForm.elements.namedItem("my-radio-button-group-name").value

The above will yield the value of a checked (or selected, as it is also called) radio button element, if any, or null otherwise.以上将产生一个选中的(或选择的,因为它也被称为)单选按钮元素的值,如果有的话,否则为null The crux of the solution is the namedItem function which works with radio buttons specifically.解决方案的关键是namedItem函数,它专门用于单选按钮。

See HTMLFormElement.elements , HTMLFormControlsCollection.namedItem and especially RadioNodeList.value , as namedItem usually returns a RadioNodeList object.请参阅HTMLFormElement.elementsHTMLFormControlsCollection.namedItem ,尤其是RadioNodeList.value ,因为namedItem通常返回RadioNodeList对象。

I use MDN because it allows one to track standards compliance, at least to a large degree, and because it is easier to comprehend than many WhatWG and W3C publications.我使用 MDN 是因为它允许人们至少在很大程度上跟踪标准合规性,并且因为它比许多 WhatWG 和 W3C 出版物更容易理解。

Shortest最短的

[...rates.children].find(c=>c.checked).value

 let v= [...rates.children].find(c=>c.checked).value console.log(v);
 <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>

directly calling a radio button many times gives you the value of the FIRST button, not the CHECKED button.多次直接调用单选按钮会为您提供 FIRST 按钮的值,而不是 CHECKED 按钮。 instead of looping thru radio buttons to see which one is checked, i prefer to call an onclick javascript function that sets a variable that can later be retrieved at will.而不是循环通过单选按钮来查看哪个被选中,我更喜欢调用一个onclick javascript 函数,该函数设置一个以后可以随意检索的变量。

<input type="radio" onclick="handleClick(this)" name="reportContent" id="reportContent" value="/reportFleet.php" >

which calls:调用:

var currentValue = 0;
function handleClick(myRadio) {
    currentValue = myRadio.value;
    document.getElementById("buttonSubmit").disabled = false; 
}

additional advantage being that i can treat data and/or react to the checking of a button (in this case, enabling SUBMIT button).另一个优点是我可以处理数据和/或对按钮的检查做出反应(在这种情况下,启用提交按钮)。

You can also loop through the buttons with a forEach-loop on the elements您还可以在元素上使用 forEach 循环遍历按钮

    var elements = document.getElementsByName('radioButton');
    var checkedButton;
    console.log(elements);
    elements.forEach(e => {
        if (e.checked) {
            //if radio button is checked, set sort style
            checkedButton = e.value;
        }
    });

An improvement to the previous suggested functions:对先前建议功能的改进:

function getRadioValue(groupName) {
    var _result;
    try {
        var o_radio_group = document.getElementsByName(groupName);
        for (var a = 0; a < o_radio_group.length; a++) {
            if (o_radio_group[a].checked) {
                _result = o_radio_group[a].value;
                break;
            }
        }
    } catch (e) { }
    return _result;
}

You can use .find() to select checked element:您可以使用.find()选择选中的元素:

var radio = Array.from(document.querySelectorAll('#rate input'))

var value = radio.length && radio.find(r => r.checked).value

My take on this problem with pure javascript is to find the checked node, find its value and pop it out from the array.我对纯 javascript 的这个问题的看法是找到选中的节点,找到它的值并将其从数组中弹出。

var Anodes = document.getElementsByName('A'),
    AValue = Array.from(Anodes)
       .filter(node => node.checked)
       .map(node => node.value)
       .pop();
console.log(AValue);

Note that I'm using arrow functions .请注意,我使用的是箭头函数 See this fiddle for a working example.请参阅此小提琴以获取工作示例。

如果您使用的是 jQuery:

$('input[name="rate"]:checked').val();

如果你使用没有 jQuery 的 javascript,你可以使用这个命令:

document.querySelector(`input[type="radio"][name=rate]:checked`).value
<form id="rates">
  <input type="radio" name="rate" value="Fixed Rate"> Fixed
  <input type="radio" name="rate" value="Variable Rate"> Variable
  <input type="radio" name="rate" value="Multi Rate" checked> Multi
</form>

then...然后...

var rate_value = rates.rate.value;

按 ID 检查值:

var CheckedValues = ($("#r1").is(':checked')) ? 1 : 0;

I used the jQuery.click function to get the desired output:我使用 jQuery.click 函数来获得所需的输出:

$('input[name=rate]').click(function(){
  console.log('Hey you clicked this: ' + this.value);

  if(this.value == 'Fixed Rate'){
    rate_value = $('#r1').value;
  } else if(this.value =='Variable Rate'){
   rate_value = $('#r2').value;
  } else if(this.value =='Multi Rate'){
   rate_value = $('#r3').value;
  }  

  $('#results').innerHTML = rate_value;
});

Hope it helps.希望能帮助到你。

If the buttons are in a form如果按钮在表单中
var myform = new FormData(getformbywhatever); myform.get("rate");
QuerySelector above is a better solution.上面的 QuerySelector 是一个更好的解决方案。 However, this method is easy to understand, especially if you don't have a clue about CSS.但是,这种方法很容易理解,尤其是在您对 CSS 没有任何了解的情况下。 Plus, input fields are quite likely to be in a form anyway.另外,输入字段很可能无论如何都在表单中。
Didn't check, there are other similar solutions, sorry for the repetition没查,还有其他类似的解决方法,抱歉重复

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

无法获得这样的单选按钮的值,而是使用

rate_value = document.getElementById('r1').value;

如果您使用的是JQuery ,请使用下面的代码段作为单选按钮组。

var radioBtValue= $('input[type=radio][name=radiobt]:checked').val();

只需使用: document.querySelector('input[rate][checked]').value

Here is a solution putting the radio buttons in a constant and getting the selected value only when needed.这是一个将单选按钮置于常量中并仅在需要时获取所选值的解决方案。

 const rates = document.forms.rates.elements["rate"] showRate() function showRate(){ document.getElementById('results').innerHTML = rates.value }
 <form id="rates" onchange="showRate()"> <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 </form> <div id="results"></div>

https://codepen.io/anon/pen/YQxbZJ https://codepen.io/anon/pen/YQxbZJ

The HTML的HTML

<div id="rates">
<input type="radio" id="x1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="x2" name="rate" value="Variable Rate" 
checked="checked"> Variable Rate
<input type="radio" id="x3" name="rate" value="Multi Rate" > Multi Rate
</div>

<button id="rdio"> Check Radio </button>
<div id="check">

</div>

The JS JS

var x ,y;
var x = document.getElementById("check");
function boom()
{
if (document.getElementById("x1").checked)
  y = document.getElementById("x1").value;

else if(document.getElementById("x2").checked)
  y = document.getElementById("x2").value;

else if (document.getElementById("x3").checked)
  y = document.getElementById("x3").value;
else
  y = "kuch nhi;"
x.innerHTML = y;
}

var z = document.getElementById('rdio');
z.addEventListener("click", boom);`

 var rates=document.getElementsByName("rate"); for (i = 0; i < rates.length; i++) { if (rates[i].checked) { console.log(rates[i].value); rate=rates[i].value; document.getElementById("rate").innerHTML = rate; alert(rate); } }
 <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> </br> <div id='rate'> </div>

In php it's very easy在php中这很容易
html page html页面

 Male<input type="radio" name="radio" value="male"><br/> Female<input type="radio" name="radio" value="female"><br/> Others<input type="radio" name="radio" value="other"><br/> <input type="submit" value="submit">

Take value from form to php从表单获取价值到 php

$radio=$_POST['radio'];<br/>
use php if(isset($_POST['submit']))<br/>
{<br/>
echo "you selected".$radio."thank u";<br/>
}

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

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