我是 Javascript 的初学者,我的 Javascript 表单对象有问题。如何遍历整个表单对象,仅选择用户选中的元素。到目前为止,我已经尝试了以下内容:
//Gets the selected checkbox values:
function getCbValues() {
var chkMouse = document.getElementById("chkMouse");
var chkKeyboard = document.getElementById("chkKeyboard");
var chkDVD = document.getElementById("chkDVD");
var chkSound = document.getElementById("chkSound");
var myFormElem = myForm.elements;
for (var i = 0; i < myFormElem.length; i++) {
if (myFormElem[i].type == "checkbox") {
if (myFormElem.checked == true) {
if (myFormElem[i].elementId == chkMouse) {
alert("This is the Mouse");
}
if (myFormElem[i].elementId == chkKeyboard) {
alert("This is the Keyboard");
}
if (myFormElem[i].elementId == chkDVD) {
alert("This is the DVD");
}
if (myFormElem[i].elementId == chkSound) {
alert("This is the Sound");
}
} else {
alert("Nothing");
}
}
}
}
我已经为所有不同的复选框Id声明了所有var。这是一个网页:
<form action="" name="form1">
<!--Checkbox table-->
<table>
<!--Select Add on Item's-->
<tr class="firstHeader">
<th colspan="3">
<h3>Select Add On Items (Optional):</h3>
</th>
</tr>
<tr>
<th colspan="2">Add On Items</th>
</tr>
<tr>
<td><label>Mouse</label>
<td><input type="checkbox" name="chkMouse" value="Mouse" id="chkMouse" price="31" /></td>
</tr>
<tr>
<td><label>Keyboard</label></td>
<td><input type="checkbox" name="chkKeyboard" value="Keyboard" id="chkKeyboard" price="42" /></td>
</tr>
如您所见,我已将表单放入表中。但我的问题是,每当我运行Javascript时,返回的值总是空值或未定义。我的问题是,如何在Javascript中使表单对象循环所有这些元素,最终只返回选中的复选框的值。有人可以帮我解决这个问题吗?提前致谢!!
慕妹3146593
相关分类