我们如何使用 DOM 访问单选按钮的值?

发布于 2024-07-14 13:55:10 字数 326 浏览 7 评论 0原文

我们如何使用 DOM 访问单选按钮的值?

例如。 我们的单选按钮为:

<input name="sex" type="radio" value="male">

<input name="sex" type="radio" value="female">

它们位于名为 form1 的表单内。 当我尝试时,

document.getElementByName("sex").value

无论检查的值如何,它总是返回“男性”。

How can we access the value of a radio button using the DOM?

For eg. we have the radio button as :

<input name="sex" type="radio" value="male">

<input name="sex" type="radio" value="female">

They are inside a form with name form1. When I try

document.getElementByName("sex").value

it returns 'male' always irrespective of the checked value.

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

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

发布评论

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

评论(12

一腔孤↑勇 2024-07-21 13:55:10

只是为了“泛化” Canavar 非常有用的功能:

function getRadioValue(theRadioGroup)
{
    var elements = document.getElementsByName(theRadioGroup);
    for (var i = 0, l = elements.length; i < l; i++)
    {
        if (elements[i].checked)
        {
            return elements[i].value;
        }
    }
}

...现在将这样引用:

getRadioValue('sex');

奇怪的是,这样的东西还没有成为 prototype.js 的一部分。

Just to "generify" Canavar's very helpful function:

function getRadioValue(theRadioGroup)
{
    var elements = document.getElementsByName(theRadioGroup);
    for (var i = 0, l = elements.length; i < l; i++)
    {
        if (elements[i].checked)
        {
            return elements[i].value;
        }
    }
}

... which would now be referenced thusly:

getRadioValue('sex');

Strange that something like this isn't already a part of prototype.js.

铜锣湾横着走 2024-07-21 13:55:10

令人惊讶的是,没有人建议实际使用 Selector API:

document.querySelector('input[name=sex]:checked').value

浏览器支持很好

Surprised no-one has suggested actually using the Selector API:

document.querySelector('input[name=sex]:checked').value

Browser support is good

暮年慕年 2024-07-21 13:55:10

如果您需要所选的一个,大多数框架都支持如下功能:

//jQuery
$("input[name='sex']:checked").val()

If you need the selected one, most frameworks support functionality like this:

//jQuery
$("input[name='sex']:checked").val()
卖梦商人 2024-07-21 13:55:10

您可以通过以下方法获取所选收音机的值:

<script>
function getRadioValue()
{
    for (var i = 0; i < document.getElementsByName('sex').length; i++)
    {
        if (document.getElementsByName('sex')[i].checked)
        {
            return document.getElementsByName('sex')[i].value;
        }
    }
}
</script>

You can get your selected radio's value by this method :

<script>
function getRadioValue()
{
    for (var i = 0; i < document.getElementsByName('sex').length; i++)
    {
        if (document.getElementsByName('sex')[i].checked)
        {
            return document.getElementsByName('sex')[i].value;
        }
    }
}
</script>
心房的律动 2024-07-21 13:55:10

有几种方法。

1. 在每个输入上放置一个 id

<input name="sex" id="sex_male" type="radio" value="male">
<input name="sex" id="sex_female" type="radio" value="female">

然后你可以使用 document.getElementById("sex_male")

2. 使用类似 PrototypeJS 的东西(jQuery 也可以)

然后你可以这样做

//This loops over all input elements that have a name of "sex"
$('input[name="sex"]').each( function(elem) {
  //Do something
});

:仅使用“male”单选按钮:

$('input[name="sex"][value="male"]').each(function(elem) {
  //Do something
});

开始使用 Prototype 的一个简单方法是通过 Google 将其包含在内将其添加到 之间 您页面的标签:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>

There are a couple of ways.

1. Put an id on each input

<input name="sex" id="sex_male" type="radio" value="male">
<input name="sex" id="sex_female" type="radio" value="female">

Then you can use document.getElementById("sex_male")

2. Use something like PrototypeJS (jQuery works too)

Then you can do something like this:

//This loops over all input elements that have a name of "sex"
$('input[name="sex"]').each( function(elem) {
  //Do something
});

Or even this to get at just the "male" radio button:

$('input[name="sex"][value="male"]').each(function(elem) {
  //Do something
});

An easy way to get started with Prototype is include it from Google by adding this between the <head></head> tags of your page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
骷髅 2024-07-21 13:55:10

如果您想要选定的一项,但没有方便的框架,您可以迭代元素数组,查找选中的一项:

for (var i = 0; i < document.form1.sex.length; i++) {
    if (document.form1.sex[i].checked) alert(document.form1.sex[i].value);
}

If you want the selected one, but don't have a framework handy, you can iterate over the element array looking for whichever one is checked:

for (var i = 0; i < document.form1.sex.length; i++) {
    if (document.form1.sex[i].checked) alert(document.form1.sex[i].value);
}
脸赞 2024-07-21 13:55:10
var list = document.getElementsByName('sex');
for(var i=0;i<list.length;i++){
   if(list[i].type=='radio' && list[i].checked){
      alert(list[i].value);
      break;
   }
}
var list = document.getElementsByName('sex');
for(var i=0;i<list.length;i++){
   if(list[i].type=='radio' && list[i].checked){
      alert(list[i].value);
      break;
   }
}
盗琴音 2024-07-21 13:55:10

如果您使用 document.form1.sex,则会返回一个数组。

document.form1.sex[0] = 第一个单选按钮

document.form1.sex[1] = 第二个单选按钮

要检查哪个单选按钮被选中,您需要循环:

whoChecked(document.form1.sex)

function whoChecked(fieldName) {
   for(var x=0;x<fieldName.length;x++) {
     if(fieldName[x].checked) {
        return fieldname[x].value
     }
}

If you use document.form1.sex, you are returned an array.

document.form1.sex[0] = first radio button

document.form1.sex[1] = second radio button

To check which is checked you need to loop:

whoChecked(document.form1.sex)

function whoChecked(fieldName) {
   for(var x=0;x<fieldName.length;x++) {
     if(fieldName[x].checked) {
        return fieldname[x].value
     }
}
挖个坑埋了你 2024-07-21 13:55:10
document.getElementByName("sex").value

您的意思是 getElementsByName('sex')[0].value? (没有 getElementByName。)

当然,这将始终选择具有该名称的第一个输入元素 - 其值确实为male 的元素。 然后,您可以使用“.checked”属性检查是否已选择它。

对于这个简单的情况,您可以逃脱:

var sex= document.getElementsByName("sex")[0].checked? 'male' : 'female';

对于一般情况,您必须循环每个无线电输入以查看哪个被检查。 首先获取表单对象可能会更好(在表单上放置一个 id 并使用 document.getElementById 通常比使用基于“名称”的 document.forms 集合更好),然后访问form.elements.sex 来获取列表,以防页面上有任何其他元素具有 name="sex" 属性(可能是表单字段之外的其他元素)。

document.getElementByName("sex").value

You mean getElementsByName('sex')[0].value? (There's no getElementByName.)

That will of course always pick the first input element with that name — the one whose value is indeed male. You then check to see if it's selected by using the ‘.checked’ property.

For this simple case you can get away with:

var sex= document.getElementsByName("sex")[0].checked? 'male' : 'female';

For the general case you have to loop over each radio input to see which is checked. It would probably be better to get the form object first (putting an id on the form and using document.getElementById is generally better than using the ‘name’-based document.forms collection), and then access form.elements.sex to get the list, in case there are any other elements on the page that have name="sex" attributes (potentially other things than form fields).

以可爱出名 2024-07-21 13:55:10
function getEleByName(){
    if(true==document.getElementsByName('gender')[0].checked){
        alert('selected gender is: male');
    }
    else{
        alert('selected gender is: female');
    }
}
function getEleByName(){
    if(true==document.getElementsByName('gender')[0].checked){
        alert('selected gender is: male');
    }
    else{
        alert('selected gender is: female');
    }
}
还给你自由 2024-07-21 13:55:10

正如其他人所展示的那样,循环可以完成该任务,但它可能比使用循环更简单,如果需要,这将有助于提高性能。 此外,它可以是便携式/模块化的,因此可以用于不同的无线电组。

简单的例子

function getValue(x) {
  alert(x.value);
}
<input name="sex" type="radio" value="male" onChange="getValue(this)" />
<input name="sex" type="radio" value="female" onChange="getValue(this)" />

一个更复杂的例子:

function getValue(x){
  alert(x.value);
}
<fieldset>
  <legend>Sex</legend>
  <label>Male:
    <input name="sex" type="radio" value="male" onChange="getValue(this)"/>
  </label>
  <label>Female:
    <input name="sex" type="radio" value="female" onChange="getValue(this)" />
  </label>
</fieldset>
<fieldset>
  <legend>Age Group</legend>
  <label>0-13:
    <input name="ageGroup" type="radio" value="0-13" onChange="getValue(this)" />
  </label>
  <label>13-18:
    <input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
  </label>
  <label>18-30:
    <input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
  </label>
  <label>30+:
    <input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
  </label>
</fieldset>

Loops can achieve the task, as others have shown but it could be simpler than using a loop, which will help performance if desired. Also, it can be portable/modular so it can be used for different radio groups.

Simple Example

function getValue(x) {
  alert(x.value);
}
<input name="sex" type="radio" value="male" onChange="getValue(this)" />
<input name="sex" type="radio" value="female" onChange="getValue(this)" />

A more complex example:

function getValue(x){
  alert(x.value);
}
<fieldset>
  <legend>Sex</legend>
  <label>Male:
    <input name="sex" type="radio" value="male" onChange="getValue(this)"/>
  </label>
  <label>Female:
    <input name="sex" type="radio" value="female" onChange="getValue(this)" />
  </label>
</fieldset>
<fieldset>
  <legend>Age Group</legend>
  <label>0-13:
    <input name="ageGroup" type="radio" value="0-13" onChange="getValue(this)" />
  </label>
  <label>13-18:
    <input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
  </label>
  <label>18-30:
    <input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
  </label>
  <label>30+:
    <input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
  </label>
</fieldset>

风吹过旳痕迹 2024-07-21 13:55:10
  • document.all.sex[0].checked
  • document.all.set[1].checked
  • document.all.sex[0].checked
  • document.all.set[1].checked
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文