Add <option> to <select> with jQuery via $.post’s callback

Asked

Viewed 2,395 times

3

I’m making a select that will have some users and when selecting a user will send a request $.post to get all records related to the selected user. After returning the related entries, the jQuery will return the callback of $.post and through the returned data I need to make a loop to add all the returned names within the <option></option>, the problem is that I do not know how to do this. The data will be returned in json by PHP and jQuery have to capture by callback and form a loop to put in <option>.

I know that to add a record to option I use the code

$('#example').append('<option value="foo" selected="selected">Foo</option>');

But I wanted to know how to loop with the json returned by callback.

2 answers

2

Assuming your return structure as:

usuarios = [
    {"id" : 1, "login": "joao"},
    {"id" : 2, "login": "maria"}
];

According to the documentation itself (the secret is here, in each function):

$.post("http://urlQueRetornaArrayEmFormatoJSON", function(retorno) {
    $.each(retorno, function(indice, usuario){  
        $("#seuSelect").append(new Option(usuario.login, usuario.id));
    });
});

or the way you’ve said you know how to do:

$.post("http://urlQueRetornaArrayEmFormatoJSON", function(retorno) {
    $.each(retorno, function(indice, usuario){  
        $('#seuSelect').append('<option value="' + usuario.id + '" slected="selected">' + usuario.login + '</option>');
    });
});

2


When the result of Ajax is a JSON, jQuery automatically converts it into a common Javascript object. That way, all you have to do is access its properties (or indexes, if it’s an array) normally. For example, if your result looks like this (line breaks added by readability):

{ "resultados":{
    "lista":[
        {"valor":"foo", "texto":"Foo"}, {"valor":"bar", "texto":"Bar"},
        {"valor":"baz", "texto":"Baz"}
    ],
    "etc":"etc" 
  },
  "etc":"etc"
}

Your code would be:

$.post(url, argumentos, function(json) {
    var lista = json.resultados.lista;
    for ( var i = 0 ; i < lista.length ; i++ ) {
        var option = $("<option></option>").appendTo($('#example'));
        option.attr("value", lista[i].valor);
        option.html(lista[i].texto);

        // ou (mais feio):
        $('#example').append('<option value="' + lista[i].valor + '">' +
                             lista[i].texto + '</option>');
    }
}, 'json');

Or if your result was something like:

{ "foo":"Foo", "bar","Bar", "baz":"Baz" }

Your code could be like this:

$.post(url, argumentos, function(json) {
    for ( var valor in json ) if( json.hasOwnProperty(valor) ) {
        var option = $("<option></option>").appendTo($('#example'));
        option.attr("value", valor);
        option.html(json[valor]);
    }
}, 'json');

Etc..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.