How to load a CSV file and then convert it into a javascript array (Compare input of form with external csv file to display specific content)
How to load a CSV file and then convert it into a javascript array (Compare input of form with external csv file to display specific content)
I'm new to javascript but this is what I've pieced together from here and w3schools.
Apologies if something similar already exists.
I want to create a page where people with a 6-character code can find out what they've won.
In my example;
I have 5 toy cars and 5 rubber duckies to give away.
(codes will eventually by randomised)
If I was to upscale this to 500 toy cars and 500 rubber duckies I believe there has to be a better way than what I have created. (below)
Is there a way to compare the input with a csv file (or other file type located online) that I can use to validate the if/else statements in
"function compareinput()" ?
I'd prefer javascript solution as opposed to PHP.
See fiddle here; https://jsfiddle.net/tn5Lp3mc/
(apologies in advanced for not compartmentalising my code, I don't know how to use jsfiddle)
function compareinput() {
var x = document.getElementById("forminput");
var text = "";
var i;
var varbl;
for (i = 0; i < x.length ;i++) {
text += x.elements[i].value + "<br>";
}
varbl = text.toUpperCase().substring(0, 6);
if (varbl == "RD1234" ||
varbl == "RD4567" ||
varbl == "RD7894" ||
varbl == "RD8454" ||
varbl == "RD9854") {
displayRubberduck ();
}
else if (varbl == "TC5678" ||
varbl == "TC1234" ||
varbl == "TC9874" ||
varbl == "TC8989" ||
varbl == "TC1212") {
displayToycar ();
}
else {
displayInvalidcode();
}
}
Thank you - I've updated the question.
– George Carmichael
Jul 3 at 6:35
“I'd prefer javascript solution as opposed to PHP.” - why? So that everyone can go look up what a valid code would be, by simply requesting the CSV resource (the URL of which you of course won’t be able to hide) themselves …?
– CBroe
Jul 3 at 6:49
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Would it be helpful to rephrase your question as "how to load a CSV file and then convert it into a javascript array? Once you achieve that, your problem becomes a matter of finding values from an array. There is a pretty good library for parsing CSV in javascript: papaparse.com
– evenstar
Jul 3 at 5:21