1

I am trying to populate a Select using an ajax call that retrieve a json with the content. As far as I see, connection is working okey (using Chrome Network option I see the ajax response always contains data, this is a example of the response when the select shows nothing: [{"id":"4","value":"VALOR 4"},{"id":"5","value":"VALOR 5"},{"id":"6","value":"VALOR 6"}]).

I am using this piece of jquery to load the select (function is called from $.ready()):

function(options) {
    $.each(options, function(key, option){
        select.append($('<option></option>').val(option['id']).text(option['value']) );
    })};

The problem is that sometimes, the select is populated and sometimes it is not, without showing any error on browser console. Indeed, I duplicate the same SELECT, and problem is happening in both of them, but not necesary at the same time: sometimes both are populated, sometimes just one, sometimes both are empty...

How should I fix/rewrite my piece of code in order to make it to work consistently?

Maria
  • 23
  • 4

1 Answers1

0

Your logic seems to be correct, so if there is an issue it's probably from the response you receive from the server

let options = [{"id":"4","value":"VALOR 4"},{"id":"5","value":"VALOR 5"},{"id":"6","value":"VALOR 6"}];


let select = $('select')
$.each(options, function(key, option){
        select.append($('<option></option>').val(option['id']).text(option['value']) );
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<select></select>
tjadli
  • 790
  • 6
  • 16