I have some code that compares the user input to a value in an array. If the user input match, i want to display an img equal to the input value.
Like this: User inputs the letter A, A is equal to letters[0], so display the img A.png.
Been trying for a while, but cant seem to get it to work? Do i need to use an associative array
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = generateLetters;
}
// Array containing every letter in the alphabet
var letters = ["A", "B", "C", "D", "A", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Æ", "Ø", "Å"];
// Array containing a img equal to the letter
var letterImages = [letters[0] = "img/A.png", letters[1] = "img/B.png", letters[2] = "img/C.png", letters[3] = "img/D.png"];
function generateLetters() {
// Get user input and convert to upper case to match array value
var input = document.getElementById("input").value.toUpperCase();
// Loops through letterImages array
for (var x = 0; x < letterImages.length - 1; x++)
// Loops through letters array
for (var i = 0; i < letters.length; i++)
// Check if input is equal to a value inside letters array
if (letters.indexOf(input) > -1) {
// Show img equal to input value
document.getElementById("img").src = letters[x];
}
}
<input id="input" type="text">
<button id="btn" type="button">Generate Letter</button>
<p id="print"></p>
<img id="img" height="50px" width="50px">
lettersis an array of type string, soletters[x]will return a string. So when you set it to src, it will never get the file as you are not passing a src.// Array containing a img equal to the letteryou're reassigning values oflettersarray, note that yourletters[0]will beimg/A.png. Is that really what you want?"A"in yourlettersarray, that's why even though you're rewriting your first instance of "A" (as stated in my previous comment) it still finds the second one