I'm kind of stuck on a problem, I’m trying to import a text file from my local computer to JavaScript and populate HTML dropdown's according to the text file. I have spent a lot of time looking at similar questions on stack overflow and i haven't found the solution to the problem yet. Here is an example of what the text file looks like:
Dogs -
Blue Dog
Black Doggo
Random Doggo
Cats -
Neon cat
Grumpy cat
Potato cat
Here is what my js looks like:
<html>
<body>
<select name="myselect">
</select>
</body>
<script>
Function GetTxt() {
var AllData = '';
var StuffFile = new XMLHttpRequest();
StuffFile.open("GET", "C:Users/Documents/Desktop/WeirdDoggos.txt",true)
StuffFile.onreadystatechange = function(){
if(StuffFile.readyStatus === 4) {
if (StuffFile.status === 200 || StuffFile.status === 0) {
AllData = StuffFile.responseText;
var lines = StuffFile.responseText.split('/n').map(function (line){
return line.trim
});
var select = $("select[name=myselect]")
var optionCounter = 0;
var currentGroup = "";
lines.forEach(function(line){
if(line.endsWith(" -")){
currentGroup = line.substring(0, line.length - 2);
optionCounter = 0;
select.append("<optgroup id='" + currentGroup + "' label='" + currentGroup + "'>")
} else if(line === ""){
select.append("</optgroup>");
} else {
select.append("<option type='checkbox' id='"
+ (currentGroup + optionCounter) + "' name='"
+ (currentGroup + optionCounter) + "' value='"
+ line + "'>" + line + "</option>");
}
});
}
}
}
}
</script>
</html>
So I’m trying to populate Select name=”MySelect” in HTML, but I don’t think it’s importing the text file, any tips?