我创建了一个表单,我希望获取用户输入的数据。 到目前为止我的javascript已经提取了所有数据。但是也会拉两个单选按钮,但只检查一个。
Q1 如何将循环限制为不拉入两个单选按钮而只拉出所选的按钮?
Q2 如果选中复选框,我该怎么办?
Q3 如何从textarea
获取数据?
先谢谢,
JS
var myNodeList = document.getElementsByName('cf');
var myArray = []; // empty Array
for (var i = 0; i < myNodeList.length; i++) {
var self = myNodeList[i];
myArray.push(self);
}
console.log(myArray)
HTML
<!DOCTYPE html>
<html>
<head>
<title>Contact Me</title>
<link rel="stylesheet" type="text/css" href="contactform_Lab8.css">
</head>
<body>
<form id="contactus">
<fieldset>
<label for="name">Name:</label>
<input id="name" type="text" name="cf" autofocus required>
<label for="email">Email:</label>
<input id="email" type="email" name="cf" required>
<label for="phone">Phone:</label>
<input id="phone" type="tel" name="cf" required>
<label for="status">Status:
<select id="status" name="cf" required>
<option value="client">Client</option>
<option value="partner">Partner</option>
<option value="vendor">Vendor</option>
</select>
</label>
<label for="subscribe">
<input id="subscribe" type="checkbox" name="cf" value="check" checked>
Send me your newsletter</label>
<label for="sales">
<label for="support">
<input id="slsSupport" type="radio" name="cf" value="sales" checked>Sales
<input id="slsSupport" type="radio" name="cf" value="support">Support
</label>
</label>
<label for="msg">Message:</label>
<textarea id="msg" name="cf" rows="10" cols="30" required></textarea>
</fieldset>
<fieldset>
<button type="submit">Send</button>
<button type="reset">Reset</button>
</fieldset>
</form>
<script src="contactform_Lab8.js"></script>
</body>
</html>
答案 0 :(得分:0)
答案 1 :(得分:0)
您可以添加一个If语句来检查元素的类型。
if(self.type === "radio" && self.checked){
myArray.push(self);
}
if(self.type !== "radio"){
myArray.push(self);
}