Javascript 如何从表单输入 type=radio 中获取值?

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

How to get value from form input type=radio?

javascripthtmlradio-button

提问by Hai Truong IT

<input type="radio" value="0" name="type" checked="yes" />
<label>Type 0</label>
<input type="radio" value="1" name="type" />
<label>Type 1</label>

and js:

和js:

var type = this.type.value;
alert(type);

How to fix it ?

如何解决?

回答by nnnnnn

In what context does that JS code run? If thisis the radio button in question then this.valuewill return the value.

该 JS 代码在什么上下文中运行?如果this是有问题的单选按钮,this.value则将返回该值。

If your question is "How do I get the value of the currently selected radio button in the 'type' group?" then you may need to do something like this:

如果您的问题是“如何获取‘类型’组中当前选定的单选按钮的值?” 那么你可能需要做这样的事情:

function getCheckedRadioValue(radioGroupName) {
   var rads = document.getElementsByName(radioGroupName),
       i;
   for (i=0; i < rads.length; i++)
      if (rads[i].checked)
          return rads[i].value;
   return null; // or undefined, or your preferred default for none checked
}

var checkedValue = getCheckedRadioValue("type");

(It would be easier with .querySelector()or .querySelectorAll(), but not all browsers support them.)

(使用.querySelector()或会更容易.querySelectorAll(),但并非所有浏览器都支持它们。)

回答by ton

Just use selectors.

只需使用选择器。

With jquery

使用 jquery

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

Or without jquery:

或者没有 jquery:

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

回答by Purag

Just use this.valueinstead of this.type.value.

只需使用this.value代替this.type.value.

this.valuewill select the value associated with the valueattribute of the input. (That's a mouthful).

this.value将选择与value输入属性关联的值。(那是一口)。

回答by jaychapani

Using jQuery you can do like this

使用 jQuery 你可以这样做

   $(function() {
        $(".rad").click(
        function() {
             alert(this.value);
        });
    });

See this JSFiddle

看到这个JSFiddle