Select with Json

Asked

Viewed 595 times

0

Hi, how are you? I am trying to make popular a select with Json that already comes selected item. I managed to make until the select population listing all the models of cars just could not already bring it selected. Can anyone help me?

var handlerCarregaMarca = function(){

        var marca = $('#tipo-id').val();
        var marcaid = $('#marca-id').val();

        console.log(marca);
        console.log(marcaid);


        $.ajax({
            type: "GET",
            url:'listarMarcas?codigo='+marca,
            dataType: "html",
            async:false,
            success: function (data) {
                // console.log(data);

                var output= '<option value="">Selecione o Tipo do Veiculo</option>';
                var dados = JSON.parse(data);

                $.each(dados, function(i, item){
                    output += '<option value="'+item.marc_id+'""'+item.marc_id == marcaid ? 'selected':''+'">'+item.marc_nome+'</option>'
                });

                $("#marca-veiculo").html(output);
                $("#marca-veiculo").trigger('chosen:updated');
            }
        });

        $(this).val(marca);

That’s the code I’m using.

  • 1

    can put an example of json return data

  • The date returns thus marc_display : "1" marc_photo : "Fiat.jpg" marc_id : "1" marc_name : "Fiat" marc_type : "1"

  • I can list everything neat, what I can’t get I’ve already selected know, I can do this in html but in json will not.

  • dataType, nay data, as William Costamilam said, is waiting for a result HTML. Switch to JSON.

1 answer

0


guy has an error in his logical operation.

try to change that:

$.each(dados, function(i, item){
  output += '<option value="'+item.marc_id+'""'+item.marc_id == marcaid ? 'selected':''+'">'+item.marc_nome+'</option>'
});

therefore:

$.each(dados, function(i, item){
  output += "<option value='"+item.marc_id+"' "+((item.marc_id == marcaid) ? 'selected':'')+">"+item.marc_nome+"</option>"
});
  • Thank you very much, it worked.

Browser other questions tagged

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