1
I’m building a script that dynamically receives a variable php array, this variable I give json_encode, and now how do I mount my select with this information? script below:
<?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>
What JSON looks like?
– Sergio
{"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"}
– Michel Henriq