As a beginner in Javascript, I have recently started learning the language in the past few weeks.
What I am looking for:
I want to create a search bar where users can enter their postcode and then the script will search through an array to find if the postcode is in any of the objects. It should then display the message found in the corresponding object.
I am able to get it to display the message, but only for the first postcode. I suspect that the issue lies within the loop.
var montering = {
"postnummer": [{
"id": "0",
"codes": ["3089", "2089"],
"msg": "Message 1"
}, {
"id": "1",
"codes": ["3088", "2088"],
"msg": "Message 2"
}]
}
var placeholder = "";
document.getElementById('melding').innerHTML = placeholder;
//Script to search array for a match
document.getElementById("searchBtn").addEventListener('click', function() {
var formInput = document.getElementById("formInput").value,
foundItem = null; //we'll store the matching value here
if (formInput === '') {
alert('Please enter a postcode');
return false;
}
for (i = 0; i < montering.postnummer.length; i++) {
if (montering.postnummer[i].codes[i] == formInput) {
foundItem = montering.postnummer[i].codes[i];
break; //we've found a match, no need to continue
}
}
if (foundItem) {
var msg = document.getElementById('melding');
melding.innerHTML += 'Message: ' + montering.postnummer[i].msg;
} else {
alert("Code Number: '" + formInput + "' Was Not Found");
}
});
<form method="get" action="input">
<fieldset>
<input id="formInput" name="formInput" type="text" placeholder="Enter your postcode" required/>
</fieldset>
</form>
<input id="searchBtn" type="submit" value="Find price">
<p id="melding">Placeholder</p>