JavaScript: I have an array. I want to check if the first element is a fieldset
OK, so here was my original problem. You don't have to read it but in case it helps: Firefox thinks <fieldset> is a form element; Chrome doesn't
Basically, Firefox and IE count the fieldset in my HTML as an element in my array, and that screws everything up. But Google Chrome does not count the fieldset as an array element. I'm trying to solve the problem by setting the new array one way if the browser counts the fieldset, and setting it a different way if it does. Here's my code. I think the problem is with the if statement.
var $ = function (id) { return document.getElementById(id); }
function check() {
var x = $("myForm");
var user = new Array();
var type = x.elements[0].type;
if (x.elements[0].nodeName=="fieldset") {
user[0] = x.elements[1].value;
user[1] = x.elements[3].value;
user[2] = x.elements[5].value;
user[3] = x.elements[2].value;
user[4] = x.elements[4].value;
user[5] = x.elements[6].value;
} else {
user[0] = x.elements[0].value;
user[1] = x.elements[2].value;
user[2] = x.elements[4].value;
user[3] = x.elements[1].value;
user[4] = x.elements[3].value;
user[5] = x.elements[5].value;
}
var answers = new Array();
answers[0] = "sample1";
answers[1] = "sample2";
answers[2] = "sample3";
answers[3] = "sample4";
answers[4] = "sample5";
answers[5] = "sample6";
var display = new Array();
for (var i=0;i<6;i++) {
if (user[i] == "") {
display[i] = "You entered nothing.";
}
else if (user[i] == answers[i]) {
display[i] = "Correct!";
}
else {
display[i] = "Wrong. The correct answer is \"" + answers[i] + "\".";
}
}
alert(display[0] + "\n" + display[1] + "\n" + display[2] + "\n" + display[3] + "\n" + display[4开发者_如何转开发] + "\n" + display[5]);
}
The problem you were having is mainly because nodeName
usually returns uppercase text (depending on the browser), and you are comparing it with lowercase fieldset
. To make it consistent you should use string's toLowerCase
function.
About the conditionals: I think a more elegant way would be to create a new filtered
array without <fieldset>
and submit button.
Finally, the way you're creating your arrays involves a little bit too much typing.
I suggest you using literal notation for creating Arrays
and Objects
.
[Demo] (click preview)
function $(id) { return document.getElementById(id); }
var filtered = [];
var elements = $("myForm").elements;
var len = elements.length;
// opt out fieldsets and submit buttons
for (var i = 0; i < len; i++) {
var el = elements[i];
if (el.nodeName.toLowerCase() != "fieldset" && el.type != "submit") {
filtered.push(el);
}
}
// specify an order (of indices)
var user = [1, 3, 5, 2, 4, 6];
// then replace numbers with element
// values from the filtered array
for (var i = 0; i < user.length; i++) {
user[i] = filtered[ user[i] ].value;
}
精彩评论