How to add options to a drop-down list using jQuery?

0

I have a function in jQuery that gets a array from PHP , through $.post . array looks like this:

array(
    '0' => array(
        'ID' => '1',
        'NOME' => 'João'
    ),
    '1' => array(
        'ID' => '2',
        'NOME' => 'Maria'
    ),
    '2' => array(
        'ID' => '3',
        'NOME' => 'Marcos'
    ),
) 

How do I, through jQuery, add option to a select with the data in that array? Example:

<select>
 <option value="ID">"NOME"</option>
</select>

This is the $.post I am receiving array from php

$.post('/consulta/usuario', {id:id}, function(dados){
        alert(dados);
}, 'json');

I get id according to the option that the user chooses, and on the php side I'm returning array :

echo json_encode($usuario);
    
asked by anonymous 20.04.2016 / 18:03

2 answers

1

There are two ways, using either an or a for loop.

I'll demonstrate using for

for(var i = 0; i < data.length; i++) {
    var id    =   data[i]['ID'];
    var name  =   data[i]['NOME'];
    var $option  =  $( '<option />' ).val(id).text(name);
    $( 'select' ).append( $option );
}

I'll leave the form of each () on your own, it's a more enjoyable implementation, you can look it up at the link: Jquery $ each ()

I hope it helps you

    
20.04.2016 / 18:15
1

I assume you get a PHP JSON, so you have PHP:

echo json_encode($array);

So in JavaScript you can iterate this object like this:

var select = document.querySelector('select');
pessoas.forEach(function(obj) {
    var opt = document.createElement('option');
    opt.value = obj.ID;
    opt.innerHTML = obj.NOME;
    select.appendChild(opt);
});

jsFiddle: link

    
20.04.2016 / 18:13