PDA

View Full Version : Resolved Problem with arrays - other strings in index being ignored


Firecrackle
09-25-2009, 10:17 AM
I'm fairly new to Javascript so greatly need some expert eyes to point me in the right direction here.

I'm making an online test and the participants would have to verify themselves by registration number before they can proceed with it. I'm trying to use an array [NoList] to index the registration numbers. This is encased in a function [checkName] that is assigned to and activated by a button. This corresponds to a text field [PartNo] where the participant puts their number and the function then checks that the input value/data matches one of the items the array index. Here is the code:

function checkName() {
var NoList = ['123456', '234561', '345612'];
Partname = document.test.PartNo.value;

for (var i in NoList) {
if (Partname != NoList[i]) {
alert("Your number "+ Partname + " has not been recognised.\nPlease check it and try again.");
return false;
}
window.open('nextstage.html');
return true;
}
}


I've done a dry run and found that the function only notices the first item in the index and ignores the others. I would be very grateful if anyone can highlight the error and suggest some alternatives. Thanks.

Spudhead
09-25-2009, 12:49 PM
The "return false" will force the function to stop. So as soon as it finds a value in NoList that doesn't match Partname, it'll stop running.

Something like this would probably work:

var Partname = document.test.PartNo.value;
var NoList = ['123456', '234561', '345612'];

var okToContinue = false;

for (var i in NoList) {
if (NoList[i] == Partname){
okToContinue = true;
}
}
if (okToContinue){
window.open('nextstage.html');
return true;
}else{
alert("Your number "+ Partname + " has not been recognised.\nPlease check it and try again.");
return false;
}


... although I'd add that as a security measure, storing the registration number they need to enter to continue, in the source code of the page that they need to enter it on, it's possibly not the fort knox of web applications :)

Firecrackle
09-25-2009, 01:11 PM
Haha, you're most certainly right with the last part but rest assured the test itself is just a minor pilot questionnaire and the registration numbers bit is really a way to ensure the participants identify themselves properly, since the HTML form will be e-mailed to those concerned to analyse.

Nevertheless, thank you for your help Spudhead - your suggestion worked like a charm. Now I know what to do in the future if I encounter a similar scenario - and I can stop tearing my hair out :thumbsup:.