简体   繁体   中英

Cannot populate a select box with jquery

I have a select box that I is been populated by jQuery. The options are gotten from the server via a REST call and are then used to populate the select box.

The application is also supposed to work offline but when offline these REST calls fail. So what I'm doing is when the REST calls actually pass, I store these values inside localStorage and when offline and the REST call fails, I just get the stored values inside the localStorage and try to populate the select box.

However the select boxes still appear empty. I've printed the stored values in the console and it shows that these values where actually successfully stored and retrieved. I'm not sure why my select boxes still appear empty.

$.getJSON("/openmrs/ws/rest/v1/location", function(result) {
  var locations = $("#identifierLocations");

  localStorage.setItem("locations", result.results);

  $.each(result.results, function() {
    locations.append($("<option />").val(this.uuid).text(this.display));
  });
}).fail(function(jqXHR, textStatus, errorThrown) {
  var data = localStorage.getItem("locations");

  if (data) {
    var locations = $("#identifierLocations");

    for (var i = 0; i < data.length; i++) {
      locations.append($("<option />").val(data[i].uuid).text(data[i].display));
    }
  }
});

I used console.log inside .fail() and I can confirm that data actually has all stored location objects but why does my select box still appears empty.

The issue is because localStorage can only hold strings. You need to serialise the result.results before storing them, then deserialise when retrieving them. Try this:

$.getJSON("/openmrs/ws/rest/v1/location", function(result) {
  localStorage.setItem("locations", JSON.stringify(result.results));
  populateLocations(result.results);
}).fail(function(jqXHR, textStatus, errorThrown) {
  var data = localStorage.getItem("locations");
  if (data) {
    populateLocations(JSON.parse(data));
  }
});

function populateLocations(locations) {
  var html = locations.map(function(o) {
    return '<option value="' + o.uuid + '">' + o.display + '</option>';
  }).join('');
  $("#identifierLocations").html(html);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM