Add option to select with jQuery through $ .post callback

2

I am 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 records, the jQuery will return the callback of the $.post and through the data returned I need to loop to add all the names returned inside the <option></option> , the problem is who do not know how to do this. The data will be returned in jSON by PHP and jQuery has to catch by the 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 the callback.

    
asked by anonymous 07.10.2014 / 06:03

2 answers

2

When the Ajax result is a JSON, jQuery automatically converts it to an ordinary JavaScript object. That way, all you have to do is access your properties (or indexes, if it's an array) normally. For example, if your result is 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 look 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.

    
07.10.2014 / 06:30
2

Assuming your return structure as:

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

According to the own documentation ( the secret is here, in the 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 already said how to do:

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