cvelinho
cvelinho

Reputation: 576

Load data from JSON

I tried to do something like this:

HTML

<select id="firstSelect">
    <option value="">Choose...</option>
    <option value="">&nbsp;</option>
    <option value="">&nbsp;</option>
</select>

Java Script

$(function () {

        $('#firstSelect').click(function () {

            $.getJSON("someService", function (data) {
                var options = '<option value="">Choose...</option>';
                $.each(data, function (index, order) {
                    options += "<option value='" + order.id + "'>" + order.title + "</option>";
                });
                $('#firstSelect').html(options);
            });
        });
}

The problem is when I first click on the select field, it doesn't fill with data from JSON, but when I clicked the 2nd time it appears and it fills in all the options.

Upvotes: 0

Views: 104

Answers (1)

Y.Puzyrenko
Y.Puzyrenko

Reputation: 2196

Do you really need to load content for the select field each time somebody clicks it ? May be it would be better if you load it on page load ? So it will solve your "works just on second click" issue. And btw you don't need to fill select field by your own.

$(document).ready(function(){
   $.getJSON("someService", function (data) {
       var options = '<option value="">Choose...</option>';
       $.each(data, function (index, order) {
          options += "<option value='" + order.id + "'>" + order.title + "</option>";
            });
       $('#firstSelect').html(options);
    });        
})

Upvotes: 1

Related Questions