仅使用HTML和JavaScript,我试图获得名字,姓氏详细信息,然后从三个单选按钮中选择喜欢的颜色。我可以得到名字和姓氏,但不能做单选按钮吗?
HTML文件:
<html>
<title>Task 3</title>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="formDetails">
First Name:<input type="text" id="firstName"><br>
Last Name:<input type="text" id="lastName"><br>
<p>Favourite Colour:</p>
<input type="radio" name="colour" value="Red">Red<br>
<input type="radio" name="colour" value="Blue">Blue<br>
<input type="radio" name="colour" value="Green">Green<br>
<input type="button" onclick="display()" value="Submit">
</form>
</body>
JavaScript文件:
function display(){
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
alert(firstName + " " + lastName);
}
我不知道如何实现单选按钮?我见过一些人使用jQuery,但我想在这里坚持使用JavaScript,因为我相当新。
感谢。
答案 0 :(得分:0)
JS:
var colour=document.querySelector('input[name="colour"]:checked').value;
alert(colour);
答案 1 :(得分:0)
步骤:
check_in
的所有输入标签添加一个类。
results
的变量中。
results
的变量
function display() {
results = {}
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var all_input = document.getElementsByClassName('check_in');
for (var i = 0; i < all_input.length; ++i) {
if (all_input[i].checked == true) {
results['option'] = all_input[i].value;
}
}
results['firstname'] = firstName;
results['lastname'] = lastName;
console.log(results);
alert('firstname:' + results['firstname'] + ' lastname: ' + results['lastname'] + ' option: ' + results['option']);
}
&#13;
margin:50px auto auto;
&#13;
<html>
<title>Task 3</title>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="formDetails">
First Name:
<input type="text" id="firstName">
<br>Last Name:
<input type="text" id="lastName">
<br>
<p>Favourite Colour:</p>
<input type="radio" name="colour" value="Red" class="check_in">Red
<br>
<input type="radio" name="colour" value="Blue" class="check_in">Blue
<br>
<input type="radio" name="colour" value="Green" class="check_in">Green
<br>
<input type="button" onclick="display()" value="Submit">
</form>
</body>
&#13;