Create a select with jquery receiving array from ajax

0

I need to dynamically create an input to list all the municipalities in a certain state of Mexico, I have my query correctly and from php I am returning the array in the following way.

    $idestado = (int)$_POST['idestado'];
    $municipios = new municipiosController();
    $listmunicipios = $municipios->getMunicipioEstado($idestado);
    echo json_encode($listmunicipios);

From ajax I receive this array and I am doing a foreach to check the information received and it is supposed that "according to" the console information everything is fine although I notice that the array has duplicate information I do not understand why, I share capture:

This is my ajax:

        $.ajax({
        url:"views/ajax.php",
        method:"POST",
        dataType: 'JSON',
        data:datos,
        cache:false,
        contentType:false,
        processData:false,
        success: function(regreso){
            Object.keys( regreso ).forEach(function( key ) {
                console.log('key name: ', key);
                console.log('value: ', regreso[key]);
            });
        }
    });

The question is: From this array that I receive, I need to generate the options in html and insert them in the select.

<div class="row">
 <div class="col-md-6">
   <label>Municipio:</label>
     <select class="selectpicker" id="selecmunicipio" name="selecmunicipio" data-live-search="true" title="Selecciona tu municipio" required>

    </select>

</div>

The HTML I need to generate is something like this:

<option  value="123">Nombre de la localidad1</option>

To finally get something like this:

<div class="row">
 <div class="col-md-6">
   <label>Municipio:</label>
     <select class="selectpicker" id="selecmunicipio" name="selecmunicipio" data-live-search="true" title="Selecciona tu municipio" required>
        <option  value="123">Nombre de la localidad1</option>
        <option  value="13423">Nombre de la localidad2</option> 
        <option  value="123223">Nombre de la localidad3</option>                
    </select>

</div>

    
asked by Neftali Acosta 10.01.2018 в 02:15
source

1 answer

1

You should iterate the data select according to the criteria and then make an append to the combo I give you an example: where list is the data set.

var combo = $('cboMicombo');
    $.each(list, function (obj, item) {    
    if(item.ciudadID== 3) {
            combo.append('<option value="' + item.Id + '">' + item.nombre + '</option>');
    }});

to see the duplicity of the data you should show the server-side code so I can help you with that.

    
answered by 10.01.2018 / 04:01
source