如何使用js获取选中的单选按钮值

发布于 2024-09-26 18:05:17 字数 160 浏览 2 评论 0原文

我正在使用此代码来获取当前选定的单选按钮的值,但它不起作用。

var mailcopy = document.getElementById('mailCopy').value; 

如何使用 Javascript 获取当前选定的单选按钮值?

I am using this code to get the value of currently selected radio button, but it doesn't work.

var mailcopy = document.getElementById('mailCopy').value; 

How to get the currently selected radio button value using Javascript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

臻嫒无言 2024-10-03 18:05:17

HTML

<p>Gender</p>
<input type="radio" id="gender0" name="gender" value="Male">Male<br>
<input type="radio" id="gender1" name="gender" value="Female">Female<br>

JS

var gender = document.querySelector('input[name = "gender"]:checked').value;
document.writeln("You entered " + gender + " for your gender<br>");

HTML

<p>Gender</p>
<input type="radio" id="gender0" name="gender" value="Male">Male<br>
<input type="radio" id="gender1" name="gender" value="Female">Female<br>

JS

var gender = document.querySelector('input[name = "gender"]:checked').value;
document.writeln("You entered " + gender + " for your gender<br>");
下壹個目標 2024-10-03 18:05:17

如果您使用 jQuery,以下代码将适合您。

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

If you are using jQuery, following code will work for you.

$('input[name=radioName]:checked').val();
浪荡不羁 2024-10-03 18:05:17

单选按钮分为具有相同名称和不同 id 的组,其中一个按钮的 check 属性设置为 true,因此循环遍历它们直到找到它。

function getCheckedRadio(radio_group) {
    for (var i = 0; i < radio_group.length; i++) {
        var button = radio_group[i];
        if (button.checked) {
            return button;
        }
    }
    return undefined;
}
var checkedButton = getCheckedRadio(document.forms.frmId.elements.groupName);
if (checkedButton) {
    alert("The value is " + checkedButton.value);
}

Radio buttons come in groups which have the same name and different ids, one of them will have the checked property set to true, so loop over them until you find it.

function getCheckedRadio(radio_group) {
    for (var i = 0; i < radio_group.length; i++) {
        var button = radio_group[i];
        if (button.checked) {
            return button;
        }
    }
    return undefined;
}
var checkedButton = getCheckedRadio(document.forms.frmId.elements.groupName);
if (checkedButton) {
    alert("The value is " + checkedButton.value);
}
赠佳期 2024-10-03 18:05:17

检查这个

<input class="gender" type="radio" name="sex" value="male">Male
<br>
<input class="gender" type="radio" name="sex" value="female">Female


<script type="text/javascript">
$(document).ready(function () {
$(".gender").change(function () {

    var val = $('.gender:checked').val();
    alert(val);
});
});

</script>

示例

check this

<input class="gender" type="radio" name="sex" value="male">Male
<br>
<input class="gender" type="radio" name="sex" value="female">Female


<script type="text/javascript">
$(document).ready(function () {
$(".gender").change(function () {

    var val = $('.gender:checked').val();
    alert(val);
});
});

</script>

Example

友欢 2024-10-03 18:05:17

也许我在这里遗漏了一些东西,但是好的旧标准 JS 不能工作吗?我的意思是:

var selectedOption = document.getElementById('your-form-name')['radio-group-name'].value;

......这当然只有在为您的无线电输入元素提供“值”时才有效。

<input type="radio" name="radio-group-name" value="red" checked>
<input type="radio" name="radio-group-name" value="blue">

在上面的示例中,该值应为“红色”或“蓝色”。

Maybe I'm missing something here, but wouldn't the good old standard JS work? I mean:

var selectedOption = document.getElementById('your-form-name')['radio-group-name'].value;

... which is only valid of course if have provided "value" for your radio input elements.

<input type="radio" name="radio-group-name" value="red" checked>
<input type="radio" name="radio-group-name" value="blue">

The value should be either 'red' or 'blue' in the above example.

醉南桥 2024-10-03 18:05:17
function getCheckedValue(radioObj, name) {

    for (j = 0; j < radioObj.rows.length; ++j) {
        for (k = 0; k < radioObj.cells.length; ++k) {
            var radioChoice = document.getElementById(name + "_" + k);
            if (radioChoice.checked) {
                return radioChoice.value;
            }
        }
    }
    return "";
}
function getCheckedValue(radioObj, name) {

    for (j = 0; j < radioObj.rows.length; ++j) {
        for (k = 0; k < radioObj.cells.length; ++k) {
            var radioChoice = document.getElementById(name + "_" + k);
            if (radioChoice.checked) {
                return radioChoice.value;
            }
        }
    }
    return "";
}
暖阳 2024-10-03 18:05:17

一种更简单的方法是使用全局 js 变量,该变量仅保存单击的单选按钮的 id。这样您就不必浪费代码在无线电列表中寻找选定的值。
当我有一个动态生成的包含 100 个或更多单选按钮的列表时,我就这样做了。通过它们旋转(几乎察觉不到)很慢,但这是一个更简单的解决方案。

您也可以使用 id 来执行此操作,但您通常只需要值。

<script>
var gRadioValue = ''; //global declared outside of function
function myRadioFunc(){
    var radioVal = gRadioValue;  
    // or maybe: var whichRadio = document.getElementById(gWhichCheckedId);
    //do somethign with radioVal
}
<script>

<input type="radio" name="rdo" id="rdo1" value="1" onClick="gRadioValue =this.value;"> One
<input type="radio" name="rdo" id="rdo2" value="2" onClick="gRadioValue =this.value;"> Two
...
<input type="radio" name="rdo" id="rdo99" value="99" onClick="gRadioValue =this.value;"> 99

A simpler way of doing this is to use a global js variable that simply holds the id of the clicked radio button. Then you don't have to waste code spinning thru your radio lists looking for the selected value.
I have done this in cases where I have a dynamically generated list of 100 or more radio buttons. spinning thru them is (almost imperceptible) slow, but this is an easier solution.

you can also do this with the id, but you usually just want the value.

<script>
var gRadioValue = ''; //global declared outside of function
function myRadioFunc(){
    var radioVal = gRadioValue;  
    // or maybe: var whichRadio = document.getElementById(gWhichCheckedId);
    //do somethign with radioVal
}
<script>

<input type="radio" name="rdo" id="rdo1" value="1" onClick="gRadioValue =this.value;"> One
<input type="radio" name="rdo" id="rdo2" value="2" onClick="gRadioValue =this.value;"> Two
...
<input type="radio" name="rdo" id="rdo99" value="99" onClick="gRadioValue =this.value;"> 99
穿越时光隧道 2024-10-03 18:05:17

你可以使用这个

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

或者,对于旧版本的jquery

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

you can use this

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

or, for older version of jquery

$('input[@name="field_value"]:checked').val();
北座城市 2024-10-03 18:05:17

由于您想使用纯 JavaScript 来获取它,因此可以使用以下代码

var val = '';
if(document.getElementById('radio1').checked) {
  val = document.getElementById('radio1').value
}else if(document.getElementById('radio2').checked) {
  val = document.getElementById('radio2').value
}

Since you want to get it using plain javascript, you can use the following code

var val = '';
if(document.getElementById('radio1').checked) {
  val = document.getElementById('radio1').value
}else if(document.getElementById('radio2').checked) {
  val = document.getElementById('radio2').value
}
り繁华旳梦境 2024-10-03 18:05:17

可能不是最有效的方法...但我在每个单选按钮上使用了 ID(这只是因为我没有将其作为实际表单传递,它只是原始字段)。

然后,我调用一个带有按钮的函数,该函数检查每个单选按钮以查看是否已选中。它使用 .checked 函数来执行此操作。如果将此设置为 true,我可以更改另一个变量的值。

function createOutput() {
  var order = "in";
  if (document.getElementById('radio1').checked == true) {
    order = "pre";
  } else if (document.getElementById('radio2').checked == true) {
    order = "in";
  } else if (document.getElementById('radio3').checked == true) {
    order = "post";
  }
  document.getElementById('outputBox').innerHTML = order;
}
<input id="radio1" type="radio" name="order" value="preorder" />Preorder
<input id="radio2" type="radio" name="order" value="inorder" checked="true" />Inorder
<input id="radio3" type="radio" name="order" value="postorder" />Postorder
<button onclick="createOutput();">Generate Output</button>
<textarea id="outputBox" rows="10" cols="50"></textarea>

希望这在某种程度上有用,

Beanz

Possibly not the most efficient way... but I have used an ID on each radio button (this is just because I'm not passing it as an actual form, it is just the raw fields).

I then call a function with a button, which checks each radio button to see if it is checked. It does this using the .checked function. If this is set to true I can change the value of another variable.

function createOutput() {
  var order = "in";
  if (document.getElementById('radio1').checked == true) {
    order = "pre";
  } else if (document.getElementById('radio2').checked == true) {
    order = "in";
  } else if (document.getElementById('radio3').checked == true) {
    order = "post";
  }
  document.getElementById('outputBox').innerHTML = order;
}
<input id="radio1" type="radio" name="order" value="preorder" />Preorder
<input id="radio2" type="radio" name="order" value="inorder" checked="true" />Inorder
<input id="radio3" type="radio" name="order" value="postorder" />Postorder
<button onclick="createOutput();">Generate Output</button>
<textarea id="outputBox" rows="10" cols="50"></textarea>

Hope this is useful, in someway,

Beanz

轻许诺言 2024-10-03 18:05:17

您可以做一些与 Beanz 的答案非常相似的事情,但不使用 ID,而是使用类来减少冗余。

function getSelectedValue() {
  var radioBtns = document.getElementsByClassName("radioBtn");
  for(var i = 0; i < radioBtns.length; i++){
    if(radioBtns[i].checked){
      document.getElementById("output").textContent = radioBtns[i].value; 
    }
  }
}
<input class="radioBtn" type="radio" name="order" value="button1" />Button 1<br>
<input class="radioBtn" type="radio" name="order" value="button2" />Button 2<br>
<input class="radioBtn" type="radio" name="order" value="button3" />Button 3<br>
<button onclick="getSelectedValue();">Get Value of Selected Radio</button><br>
<textarea id="output"></textarea>

You could do something very similar to Beanz's answer but instead of using IDs, use classes to reduce redundancy.

function getSelectedValue() {
  var radioBtns = document.getElementsByClassName("radioBtn");
  for(var i = 0; i < radioBtns.length; i++){
    if(radioBtns[i].checked){
      document.getElementById("output").textContent = radioBtns[i].value; 
    }
  }
}
<input class="radioBtn" type="radio" name="order" value="button1" />Button 1<br>
<input class="radioBtn" type="radio" name="order" value="button2" />Button 2<br>
<input class="radioBtn" type="radio" name="order" value="button3" />Button 3<br>
<button onclick="getSelectedValue();">Get Value of Selected Radio</button><br>
<textarea id="output"></textarea>

半城柳色半声笛 2024-10-03 18:05:17

大家可以测试一下这个例子,很容易理解。

        Name:   <input type="text" id="text" class ="input">
                <input type="text" id="text1" class ="input">
        Gender: <input type="radio" id="m" class="Rm"  name="Rmale" value="Male">
                <input type="radio" id="f" class="Rm" name="Rfemale" value="Female">
        Course: <input type="checkbox" id="math" class="cm" name="Cmath" value="Math">
                <input type="checkbox" id="physic" class="cm" name="Cphysic" value="Physic">
                <input type="checkbox" id="eng" class="cm"  name="Ceng" value="English">
        <button type="button" id="b1">show</button>

// JavaScript

    <script>
        function getData(input){
            return document.getElementById(input).value;
        }
        function dataByClassName(st){
            var value=document.getElementsByClassName(st)
            for(var i=0;i < value.length;i++){
                if(value[i].checked){
                    return value[i].value;
                }
            }
        }
        document.getElementById("b1").onclick = function ()
        {
            var st={
                name : getData("text")+getData("text1"),
                gender : dataByClassName("Rm"),
                course : dataByClassName("cm")
            };
            alert(st.name+" "+st.gender+" "+st.course);
        };

    </script>

all of you can test this example and easy to understand.

        Name:   <input type="text" id="text" class ="input">
                <input type="text" id="text1" class ="input">
        Gender: <input type="radio" id="m" class="Rm"  name="Rmale" value="Male">
                <input type="radio" id="f" class="Rm" name="Rfemale" value="Female">
        Course: <input type="checkbox" id="math" class="cm" name="Cmath" value="Math">
                <input type="checkbox" id="physic" class="cm" name="Cphysic" value="Physic">
                <input type="checkbox" id="eng" class="cm"  name="Ceng" value="English">
        <button type="button" id="b1">show</button>

// javascript

    <script>
        function getData(input){
            return document.getElementById(input).value;
        }
        function dataByClassName(st){
            var value=document.getElementsByClassName(st)
            for(var i=0;i < value.length;i++){
                if(value[i].checked){
                    return value[i].value;
                }
            }
        }
        document.getElementById("b1").onclick = function ()
        {
            var st={
                name : getData("text")+getData("text1"),
                gender : dataByClassName("Rm"),
                course : dataByClassName("cm")
            };
            alert(st.name+" "+st.gender+" "+st.course);
        };

    </script>
深海不蓝 2024-10-03 18:05:17

试试这个,我希望这个能起作用

function loadRadioButton(objectName, selectedValue) {

    var radioButtons = document.getElementsByName(objectName);

    if (radioButtons != null) {
        for (var radioCount = 0; radioCount < radioButtons.length; radioCount++) {
            if (radioButtons[radioCount].value == selectedValue) {
                radioButtons[radioCount].checked = true;
            }
        }
    }
}

Try this, I hope this one will work

function loadRadioButton(objectName, selectedValue) {

    var radioButtons = document.getElementsByName(objectName);

    if (radioButtons != null) {
        for (var radioCount = 0; radioCount < radioButtons.length; radioCount++) {
            if (radioButtons[radioCount].value == selectedValue) {
                radioButtons[radioCount].checked = true;
            }
        }
    }
}
后知后觉 2024-10-03 18:05:17

如果您可以使用 jQuery“Chamika Sandamal”答案是正确的方法。如果您无法使用 jQuery,您可以执行以下操作:

function selectedRadio() {
    var radio = document.getElementsByName('mailCopy');
    alert(radio[0].value);
}

注释:

  • 一般来说,对于您希望具有唯一 ID 的输入(不是要求,而是一个好的实践),
  • 所有无线电输入来自同一组必须具有相同的名称属性,例如
  • 您必须为每个输入设置值属性

以下是输入单选的示例:

<input type="radio" name="mailCopy" value="1" />1<br />
<input type="radio" name="mailCopy" value="2" />2<br />

If you can use jQuery "Chamika Sandamal" answer is the correct way to go. In the case you can't use jQuery you can do something like this:

function selectedRadio() {
    var radio = document.getElementsByName('mailCopy');
    alert(radio[0].value);
}

Notes:

  • In general for the inputs you want to have unique IDs (not a requirement but a good practice)
  • All the radio inputs that are from the same group MUST have the same name attribute, for example
  • You have to set the value attribute for each input

Here is an example of input radios:

<input type="radio" name="mailCopy" value="1" />1<br />
<input type="radio" name="mailCopy" value="2" />2<br />
绮筵 2024-10-03 18:05:17

用途:

document.querySelector('#elementId:checked').value;

这将返回所选单选按钮的值。

Use:

document.querySelector('#elementId:checked').value;

This will return the value of the selected radio button.

匿名的好友 2024-10-03 18:05:17

请尝试这个:

this.template.querySelector('input[name = "gender"]:checked').value;

Please try this:

this.template.querySelector('input[name = "gender"]:checked').value;
昵称有卵用 2024-10-03 18:05:17
var mailcopy = document.getElementById('mailCopy').checked; 

if(mailcopy==true)
{
  alert("Radio Button Checked");
}
else
{
  alert("Radio Button un-Checked");
}
var mailcopy = document.getElementById('mailCopy').checked; 

if(mailcopy==true)
{
  alert("Radio Button Checked");
}
else
{
  alert("Radio Button un-Checked");
}
失去的东西太少 2024-10-03 18:05:17

嘿,你必须这样做。

function checkRadio () {
    if(document.getElementById('user1').checked) {
        return $('#user1').val();
    }else if(document.getElementById('user2').checked) {
        return $('#user2').val();
    }
}

Hy, you have to do it this way.

function checkRadio () {
    if(document.getElementById('user1').checked) {
        return $('#user1').val();
    }else if(document.getElementById('user2').checked) {
        return $('#user2').val();
    }
}
紫南 2024-10-03 18:05:17

使用 element.checked 属性。

Use the element.checked property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文