lundi 1 juillet 2019

How to set a variable to fulfill a condition outside a for loop cycle?

problem:

I created a search form where the user is asked to insert a string into an input form. The string is the name of the city and if it matches one of the 50 cities I have included into a JSON file some function is called. We may have three conditions:

1) The input form is left empty an error log appears.

2) The input form is not empty and the string matches one of the 50 strings in the JSON file a table is displayed.

3) The input form is not empty but the string doesn’t match any of the 50 strings in the JSON file a modal window is displayed

My problem is how and where to write the command:

$(‘#Modal#).show()

In other terms, how and where should I show the modal window whenever the city inserted doesn’t match with any of those included in my JSON file?

I have a cycle for: here the value of the strings in the JSON file is being checked; I wouldn’t put the command into there, otherwise the modal will be called 49 times: since I have 50 cities, one of them matches the string inserted in the input form but the other 49 don't.

I suppose I should create a new variable with a function outside the for loop cycle, setting the condition : "the string matches one and only one of the strings in the JSON file"; then the condition may be true inside the for loop (and then I display the table), whereas it's false outside the for loop (i.e. "if the number of cities found is 0" and then I show the modal window).

The code I wrote so far is the following:

function validateCitta() {
  let text = $('#inlineFormInputCitta').val();
  if (text === "") {
    $("#errorLog").show();
  } else {
    $("#errorLog").hide();
    $.ajax({
      url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCity").val()) + "&format=geocodejson",
      dataType: "json",
      success: function(data) {
        for (let i = 0; i < data.features.length; i++) {
          let typeCity = data.features[i].properties.geocoding.type;
          if (typeCity === "city") {
            let nameCity = data.features[i].properties.geocoding.name;
            for (let i = 0; i < json.tappe.length; i++) {
              let tappa = json.tappe[i];
              let city = json.tappe[i].city;
              if (city === nameCity) {
                console.log("JSON file has been activated");
                $("#tbody").append("<tr><td>" + tappa.name + "</td><td>" + tappa.state + "</td><td>" + tappa.region + "</td><td>" + tappa.city + "</td></tr>");
                $("#tabella").show();
              };
            };
          }
        }
      }
    })
  }
};

How may I set the new variable to fulfill the third 3) condition above?

Aucun commentaire:

Enregistrer un commentaire