1

Estou montando um script que recebe dinamicamente uma variavel array do php, esta variavel eu dou json_encode, e agora como faço pra montar meu select com essas informações? script abaixo:

     <?php 
     $opts = array();
     foreach($amenities as $amenitie){
     $opts[$amenitie->id] = $amenitie->name; 
      }
     ?>

    <html>
    <head>
    <meta charset="utf-8">
    <title>Detalhes ao redor</title>
    <!--Le CSS
    ==========================================================-->
    <link href="<?php echo base_url(); ?  >includes/bootstrap/css/bootstrap.css" rel="stylesheet">
    <script    src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

      <!--Le JavaScript
      ==========================================================-->
      <script src="<?php echo base_url(); ?  >includes/bootstrap/js/bootstrap.js"></script>             
      <script>
        var _detalhes = new Array;
        var _opts = <?php echo json_encode($opts)?>;            
        function AddFoto(){
            var _i = _detalhes.length;
            var _x = _i + 1;
            var _html = '<div class="input file"><label for="amenitie_    '+_i+'">Detalhe '+_x+'</label><select name="amenitie_'+_x+'"      id="amenitie_'+_x+'" class="form-control"></select></div>';
            _detalhes[_i] = _html;                
            $("#select-form").append(_html);
            var select = document.getElementById('amenitie_'+_x+'');
            montarSelect(select, _opts);
            }

            function montarSelect(select, json) {
            if (typeof json == 'string') json = JSON.parse(json);
            Object.keys(json).forEach(function (chave) {
                var option = document.createElement('option');
                option.value = chave;
                option.innerHTML = json[chave];
                select.appendChild(option);
             });
             }

         </script>
         </head>
        <body>       
        <?= $menu ?>
       <div class="container">
        <button class="btn btn-default" id="show-button"   onclick="AddFoto()">Inserir Novo</button>
         <div class="form-select" id="select-form"></div>
     </div>
     <?= $footer ?>
     </body>
2
  • Como fica o JSON?
    – Sergio
    25/10/2015 às 15:09
  • {"2":"Seguran\u00e7a 24hs","3":"Biciclet\u00e1rio","4":"Ar Condicionado","5":"Quintal","6":"Sacada","7":"Lareira","8":"Mobiliado","9":"Dep\u00f3sito","10":"Sistema de Alarme","11":"Condom\u00ednio Fechado","12":"Interfone","13":"Churrasqueira","14":"Elevador","15":"Academia","16":"Piscina","17":"Quadra Poliesportiva","18":"Jardim","19":"Espa\u00e7o Gourmet","20":"Playground","21":"Sal\u00e3o de Festas"} 25/10/2015 às 15:15

1 Resposta 1

1

Para montar um select com JSON no formato {chave: valor} há algumas decisões que tens de tomar.

Tendo em conta que o HTML tem pelo menos 2 pontos onde podes colocar conteúdo:

<option value="ponto_1">ponto_2</option>

vou dar um exemplo onde a chave vai para o ponto_1 e o valor para o ponto_2.

function montarSelect(select, json) {
    if (typeof json == 'string') json = JSON.parse(json);
    Object.keys(json).forEach(function (chave) {
        var option = document.createElement('option');
        option.value = chave;
        option.innerHTML = json[chave];
        select.appendChild(option);
    });
}

Basicamente percorres todas as chaves desse objeto com o forEach e a cada uma crias uma nova option que recebe value e innerHTML e depois é inserida no select.

O resultado seria assim: http://jsfiddle.net/fudh3xyo/

0

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .