0

I'm trying to create a dropdown list of dates from firebase data. But the list has no options and I'm getting no errors in the console. Here's the code:

<script>

var dates = [];
$.getJSON("https://earthquake-detection-default-rtdb.firebaseio.com/X-Axis.json", function(data){
    $.each(data, function(key, value){
        if (dates.indexOf(value.date) === -1) {
                    dates.push(value.date);
            }
    })
});

console.log(dates);

var sel = document.getElementById("arr");
for(var d=0; d<dates.length; d++) {
        var dateElem = document.createElement("option");
        dateElem.value = dates[d];
        dateElem.textContent = dates[d];
        sel.appendChild(dateElem);
    } 

</script>

I'm getting the output if I do this:

<script>

var dates = ["2021-03-06","2021-04-05"];
console.log(dates);

var sel = document.getElementById("arr");
for(var d=0; d<dates.length; d++) {
        var dateElem = document.createElement("option");
        dateElem.value = dates[d];
        dateElem.textContent = dates[d];
        sel.appendChild(dateElem);
    } 

</script>

I don't understand what I'm doing wrong.

1 Answers1

0

The $.getJSON callback happens asynchronously. You need to pull out the dates after you get the response back, then call your function to populate the <select>.

Note: If you are using jQuery it should be all or nothing. Do not mix and match $('#id') with document.querySelector('#id') and document.getElementById('id').

var apiRequestAxis = 'https://earthquake-detection-default-rtdb.firebaseio.com/X-Axis.json';

function updateSelect($select, dates) {
  $select.empty();
  $.each(dates, function(index, date) {
    $select.append($('<option>').val(date).text(date));
  });
};

$.getJSON(apiRequestAxis, function(data) {
  var $sel = $("#arr"), dates = [];
  $.each(data, function(key, value) {
    if (!dates.includes(value.date)) {
      dates.push(value.date);
    }
  });
  console.log(dates);
  updateSelect($sel, dates);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="arr"></select>

Here is a more advanced example:

var apiRequestAxis = 'https://earthquake-detection-default-rtdb.firebaseio.com/X-Axis.json';

(function($) {
  var defaultOptions = {
    valueField: 'value',
    textField: 'text'
  };
  $.fn.populateSelect = function(items, options) {
    var $self = this;
    var opts = $.extend({}, defaultOptions, options);
    $self.empty();
    $.each(items, function(index, item) {
      var value = typeof item === 'string' ? item : item[opts.valueField];
      var text = typeof item === 'string' ? item : item[opts.textField];
      $self.append($('<option>').val(value).text(text));
    });
    return $self;
  };
})(jQuery);

$.getJSON(apiRequestAxis, function(data) {
  $("#arr").populateSelect(
    [...data.reduce((acc, { date }) => acc.add(date), new Set)].sort()
  );
});

$('#arr-2').populateSelect([
  { value: 1, text: 'One' },
  { value: 2, text: 'Two' },
  { value: 3, text: 'Three' }
]);

$('#arr-3').populateSelect([
  { id: '0001', name: 'Bruce' },
  { id: '0002', name: 'John' },
  { id: '0003', name: 'Sam' }
], {
  valueField: 'id',
  textField: 'name'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="arr"></select>
<select id="arr-2"></select>
<select id="arr-3"></select>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132