Sia Sia - 2 months ago 6
HTML Question

Javascript - check if key is not in data

I am trying to create a function that let's me know if my key is in my data or not.



data = [{
"1" : ["1007","1020"],
"2" : ["1200","1493"],
"3" : ["6754","8652"],
}]

document.getElementById("input").addEventListener("keyup", myFunction);
function myFunction() {
var value = document.getElementById('input').value;
for (var i = 0; i < data.length; i++) {
for (var key in data[i])
{
if (key in data[i]) {
if (data[i][key].indexOf(value) !== -1){
document.getElementById('text').innerHTML = key;

}
}

}
}
}

<div id="text"></div>
<input id="input" />





What this code does is that he checks if the number insered in the input is in data and displays his group number into the div. But what if the number is not in the data ? I want to be able to display it as '0' in the div if the number doesn't exist in my data.

Answer

data = [{
  "1" : ["1007","1020"],
  "2" : ["1200","1493"],
  "3" : ["6754","8652"],
}]

document.getElementById("input").addEventListener("keyup", myFunction);
function myFunction() {
    var value = document.getElementById('input').value;
    var foundIt = false;
    for (var i = 0; i < data.length && !foundIt; i++) {
        for (var key in data[i])
        {
            if (key in data[i]) {
                if (data[i][key].indexOf(value) !== -1){
                    document.getElementById('text').innerHTML = key;
                    foundIt = true;

                } 
            }

        }
        if (!foundIt) {
            document.getElementById('text').innerHTML = 0;
        }
    }
}
<div id="text"></div>
<input id="input" />

Comments