Lieutenant Dan
Lieutenant Dan

Reputation: 8274

check if user input value matches JSON entry ID/value

Here is what my JSON looks like (each data entry/set) via /locations.json

{
 "20101":{ // I use zip value as an entry ID, so check if this matches .val()
    "Zipcode":"20101",
    "City":"",
    "Primary State":"Virginia",
    "Lotto":"49530",
    "County":"Loudoun"
} // .... etc more entries

Here is my web form HTML mark-up:

<form action="">
   <input type="text" name="Zipcode" id="Zipcode" value="" maxlength="5" placeholder="Zipcode">
   <input type="button" name="submit" id="submit" value="Submit">
</form> 

console.log(myjson[ZipSearch]); # Works but I need to handle in if or for statement

Heres the jQuery; I have tried defining my JSON as a const and a few other things; including filter / any Ideas how I can simply check for this match in a if or for statement so I can continue handling my data?

$(document).ready(function() {
    $("#submit").click(function() {
        var ZipSearch = $("#Zipcode").val();
        console.log(ZipSearch)
        var myjson;
        $.getJSON("locations/locations.json", function(json) {
            myjson = json;
            console.log(myjson[ZipSearch]); 

        });
    });
});

latest attempt: (but it always returns as failed)

$(document).ready(function() {
    $("#submit").click(function() {
        var ZipSearch = $("#Zipcode").val();
        console.log(ZipSearch)
        var myjson;
        $.getJSON("locations/locations.json", function(json) {
            myjson = json;
            for (var key in json) {
                // console.log(key);
                if (key === ZipSearch) {
                    console.log("Pass")
                    console.log(myjson[ZipSearch]); 
                    $('.error').hide();
                } else { 
                    console.log("Fail")
                    $('.error').show();
                }
            }

        });
    });
});

Upvotes: 1

Views: 814

Answers (1)

Alen.Toma
Alen.Toma

Reputation: 4870

try this instead. If your doing for loop then you have to break it once its pass. But doing a for loop is a waste of time, try to find if the variable exist instead.

Have a look below

   $(document).ready(function() {
        $("#submit").click(function() {
            var ZipSearch = $("#Zipcode").val();
            console.log(ZipSearch)
            var myjson;
            $.getJSON("locations/locations.json", function(json) {
                myjson = json;
                if (myjson[ZipSearch]){// if exist 
                        console.log("Pass")
                        console.log(myjson[ZipSearch]); 
                        $('.error').hide();
                }else {
                      console.log("Fail")
                      $('.error').show();
                }
            });
        });
    });

Upvotes: 1

Related Questions