【发布时间】:2020-06-23 00:41:55
【问题描述】:
我有一个网站要求用户通过无线电输入选择男性或女性选项。当我选择了男性或女性时,我很难将消息输出到控制台。我不确定为什么我的 javascript 没有输出相关的 console.log 消息。 任何帮助将非常感激。 相关代码如下
var height, weight, measurementUnit;
//If male is selected
if (document.getElementById('gender_male').checked) {
console.log('male selected');
}
// if female is selected
else if (document.getElementById('gender_female').checked) {
console.log('female selected');
}
// if no gender is selected output and error
else {
console.log('no gender selected');
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="resources/css/styles.css">
<link rel="stylesheet" type="text/css" href="vendors/css/grid.css">
<link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel='stylesheet' type='text/css'>
<script type="module" src="https://unpkg.com/ionicons@5.0.0/dist/ionicons/ionicons.esm.js"></script>
<script nomodule="" src="https://unpkg.com/ionicons@5.0.0/dist/ionicons/ionicons.js"></script>
<title>BMI calculator</title>
</head>
<body>
<h1>Body Mass Index(BMI)</h1>
<div class="content">
<div class="col span-1-of-2 left">
<h2>Calculator</h2>
<ion-icon name="man"></ion-icon>
<input type="radio" name="gender" id="gender_male" value="male"> Male
<ion-icon name="woman"></ion-icon>
<input type="radio" name="gender" id="gender_female" value="female"> Female
<br>
<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
<div class="text"></div>
</label>
<br>
<label for="height">Height:</label>
<input type="number" id="height" name="height">
<br>
<label for="weight">Weight:</label>
<input type="number" id="weight" name="weight">
<br>
<a href="#" class="btn">Calculate</a>
</div>
<div class="col span-1-of-2 right">
<h2>What is a BMI?</h2>
</div>
</div>
<script src="resources/js/app.js"></script>
</body>
</html>
【问题讨论】:
-
默认情况下,您的男性和女性单选按钮未选中。这就是为什么它没有显示控制台。我认为您需要使用单选按钮绑定事件。该事件的 onClick 将控制选定的值。 w3schools.com/js/tryit.asp?filename=tryjs_form_radio
-
你在哪里调用你的javascript?
标签: javascript input radio