我有选择年龄选项的表单元素,并且使用JavaScript循环创建了年龄选项,然后在提交表单后尝试读取所选选项的值。控制台将所选选项的值显示为var I而不是所选的实际值。
以下是代码笔与代码的链接:https://codepen.io/anon/pen/wxLPpb?editors=1111
<!DOCTYPE html>
<html lang="en">
<head>
<title>Parag Patel</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
<div class='container'>
<label for="select">Select your age:</label>
<select class="form-control" id="age" name="age">
<script type="text/javascript">
for (var i = 0; i < 200; i++) {
document.write('<option value="i">' + i + '</option>');
}
</script>
</select>
</div>
<script type="text/javascript">
var formInput = document.querySelector('#age');
document.querySelector('#sub').addEventListener('click', function(e) {
e.preventDefault();
console.log('Age: ' + formInput.value);
});
</script>
</body>
</html>
答案 0 :(得分:2)
您没有在值属性中正确连接 i 变量。
for (var i = 0; i < 200; i++) {
document.write ('<option value="' + i + '">' + i + '</option>');
}
答案 1 :(得分:1)
您正在将值“ i”分配给您的选项。要将变量插入字符串中,只需执行以下操作:
for (var i = 0; i < 200; i++) {
document.write ('<option value="'+i+'">' + i + '</option>');
}