Home > Software design >  I am trying to parse two JSON objects retrieved from text fields in my HTML to retrieve values from
I am trying to parse two JSON objects retrieved from text fields in my HTML to retrieve values from

Time:04-25

Like the title says, a user inputs into two fields on my HTML file. I am trying to take these two fields, assign them a variable in JS and depending on what they type in, a result is given from a JSON file. Am I missing something? I can get it to work if I am just using one user-inputted value, but I cannot seem to make two values work properly. Here is the link to the JSON file:JSON File

function listCities() {
    var c = document.getElementById("country");
    var s = document.getElementById("subcountry");
    var answer = document.getElementById("textarea1");
    var citiesArray = JSON.parse(data);
    var output = ""
    for(obj of citiesArray) {
        if(obj.country == c.value && obj.subcounty == s.value) {
            output  = `${obj.name}\n`;
        }
    }
    answer.value = output;
}

CodePudding user response:

I just created a working demo and it is working fine. Please have a look and let me know if any further changes required as part of the requirement.

function listCities() {
    var c = document.getElementById("country");
    var s = document.getElementById("subcountry");
    var answer = document.getElementById("textarea1");
    var citiesArray = [{
        country: 'country1',
      subcountry: 'subcountry1',
      name: 'name1'
    }, {
      country: 'country1',
      subcountry: 'subcountry1',
      name: 'name2'
    }, {
      country: 'country1',
      subcountry: 'subcountry1',
      name: 'name3'
    }];
    var output = ""
    for(obj of citiesArray) {
        if(obj.country == c.value && obj.subcountry == s.value) {
            output  = `${obj.name}\n`;
        }
    }
    answer.value = output;
}
Country : <input type="text" id="country" name="country"/>
Sub Country : <input type="text" id="subcountry" name="subcountry"/>
<input type="button" value="List Cities" onclick="listCities()"/>
<br><br>
<textarea id="textarea1" name="textarea1"></textarea>

CodePudding user response:

The JSON.parse() function returns with an object, not an array. Perhaps that makes error.
You have wrong typing: obj.subcounty.

  • Related