JavaScript 检查单选按钮

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

JavaScript checking radio buttons

javascriptif-statementradio-button

提问by Maximillian Nahbai

Ok, this is really a simple question but I am really incompetent at JavaScript.

好吧,这确实是一个简单的问题,但我真的不擅长 JavaScript。

Basically all I have a form with 2 radio buttons on them.

基本上所有我都有一个带有 2 个单选按钮的表单。

I need a JavaScript statement which basically says

我需要一个 JavaScript 语句,它基本上说

If radiobutton1 is selected then
document.write ("radiobutton1selected")
else if radiobutton2 is selected then
document.write ("radiobutton2selected")

There are similar questions on here i accept but they are all alot more advanced than what i need.

我接受这里有类似的问题,但它们都比我需要的要先进得多。

回答by Ibu

Radio button html:

单选按钮html:

<input type="radio" name="radionbutton" value="1" id="button1"/>
<input type="radio" name="radionbutton" value="2" id="button"/>

Javascript:

Javascript:

var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");

if (button1.checked){
    alert("radio1 selected");
}else if (button2.checked) {
    alert("radio2 selected");
}

回答by Alex Wayne

http://jsfiddle.net/Squeegy/KCT8h/

http://jsfiddle.net/Squeegy/KCT8h/

html

html

<input type="radio" name="zing" id="foo" checked/>
<input type="radio" name="zing" id="bar"/>?

js

js

if (document.getElementById('foo').checked) {
    alert('foo');
} else {
    alert('bar');
}?

回答by cssGEEK

This is simple:

这很简单:

var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
alert(button1.checked?"Button1 is checked":"Button2 is checked");