Blockquote
How do i loop through this array and check if the user input exists in the array. If the user writes 'fanta' in the input field, i want to print 'fanta' and '27'"
const prisArr = [
{ vare: 'pepsi', pris: 30 },
{ vare: 'fanta', pris: 27 },
{ vare: 'escada', pris: 108 },
{ vare: 'dahls', pris: 69 },
{ vare: 'karsk', pris: 200 },
];
function vareSok() {
for (let i = 0; i < prisArr.length; i ) {
if (inpVare == prisArr[i]['vare']);
document.getElementById(
'resultat'
).innerHTML = `Varen med navn ${inpVare} koster ${pris} kroner!`;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<input type="text" id="sok" />
<button id="sjekkVare" onclick="vareSok()">Trykk her for å sjekke</button>
<p id="resultat"></p>
<script>
CodePudding user response:
I rewrote your code. If user type "fanta" and click on button, the result is going to be "Varen med navn fanta koster 27 kroner!"
const prisArr = [
{ vare: 'pepsi', pris: 30 },
{ vare: 'fanta', pris: 27 },
{ vare: 'escada', pris: 108 },
{ vare: 'dahls', pris: 69 },
{ vare: 'karsk', pris: 200 },
];
function vareSok() {
let userInput = document.getElementById('sok').value
for (let i = 0; i < prisArr.length; i ) {
if (prisArr[i].vare === userInput) {
document.getElementById(
'resultat'
).innerHTML = `Varen med navn ${userInput} koster ${prisArr[i].pris} kroner!`;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
<body>
<input type="text" id="sok" />
<button id="sjekkVare" onclick="vareSok()">Trykk her for å sjekke</button>
<p id="resultat"></p>
<script src="./index.js"></script>
</body>
</html>
CodePudding user response:
const prisArr = [
{ vare: 'pepsi', pris: 30 },
{ vare: 'fanta', pris: 27 },
{ vare: 'escada', pris: 108 },
{ vare: 'dahls', pris: 69 },
{ vare: 'karsk', pris: 200 },
];
function vareSok() {
for (let i = 0; i < prisArr.length; i ) {
if(prisArr[i].vare === inpVare) {
document.getElementById(
'resultat'
).innerHTML = `Varen med navn ${inpVare} koster
${prisArr[i].pris} kroner!`;
}
}
}
vareSok();
I think you're using the wrong syntax for getting the data. The if statement should be dot notation as you are referencing a key in an object. i is iterating over each object in the array. Then just change pris to prisArr[i].pris and it should work :)