为什么我从单选按钮获得相同的值? [英] Why do I get the same value from radio buttons?
本文介绍了为什么我从单选按钮获得相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,我有三个单选按钮。我想将它们的值赋给变量,但无论点击哪个按钮,值都保持不变。
我尝试过:
HTML
Hi, guys I have three radio buttons. I want to assign value of them to a variable but the value stays the same whichever button is clicked.
What I have tried:
HTML
<input type="radio" name="age" onclick="checkAge(this)" value="child">less tan 18<br>
<input type="radio" name="age" onclick="checkAge(this)" value="adult">over 18<br>
<input type="radio" name="age" onclick="checkAge(this)" value="senior">over 65<br>
JavaScript
JavaScript
function checkAge(radio){
var age = "";
if(radio.value="child"){
age = "child";
}
else if (radio.value="adult") {
age = "adult";
}
else {
age = "senior";
}
console.log(age);
}
变量'age'的值没有变化,为什么?
The value of the variable 'age' is not changing, why?
推荐答案
使用==
而不是=
use==
instead of=
if (radio.value == "child") {
但是这将完成这项工作
but this will do the job
function checkAge(radio) {
console.log(radio.value);
}
你错过了==。请打开以下链接( Tryit Editor v3.3 [ ^ ])并复制代码以进行验证。
You have missed "==". Please open the below link (Tryit Editor v3.3[^]) and copy the code to verify.
<!DOCTYPE html>
<html>
<body>
<script>
function checkAge(radio){
alert(radio.value);
var age = "";
if(radio.value=="child"){
age = "child";
}
else if (radio.value=="adult") {
age = "adult";
}
else {
age = "senior";
}
alert(age);
}
</script>
<form action="">
<input type="radio" name="gender" onclick="checkAge(this)" value="child"> child<br>
<input type="radio" name="gender" onclick="checkAge(this)" value="adult"> adult<br>
<input type="radio" name="gender" onclick="checkAge(this)" value="senior"> senior
</form>
<p> * The selected value will be shown in the alert box upon select. </p>
</body>
</html>
谢谢。
Thank you.
这篇关于为什么我从单选按钮获得相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文