I'm having trouble trying to populate a dropdown list using ´jquery´. I have an array of objects called Newjson, and I'm trying to fill a dropdown list with this data. NOTE: I've got the data through AJAX, the data was stored in a plain object called json
, I've manipulated that object in order to reverse it, transforming it into an array of objects.
Some HTML code of the dropdown list that I'm trying to configure:
<div>
<h2>Lista de Grupos</h2>
<form method="post">
<input type="hidden" name="form" value="alunos" />
<div>
<label for="IDUnidade">Unidade</label>
<select id="IDUnidade" name="IDUnidade">
<option value="">Selecione...</option>
</select>
</div>
<div>
<label for="titulo">Visita</label>
<select id="titulo" name="titulo">
<option value="">Selecione...</option>
</select>
</div>
<div class="form-control">
<button type="submit" name="submit"
value="manage">Enviar</button>
</div>
</form>
</div>
Here's what I've tried, the javascript code, to be exact:
jQuery(document).ready(function($){
$('#IDUnidade').on('change', function(){
$.ajax({
url: location.href,
dataType: 'json',
data: $(this).attr('name') +'='+ $(this).val(),
success: function(json){
$('#titulo').html('<option value="">Selecione...</option>');
const reversedKeys = Object.keys(json).reverse();
const newjson = reversedKeys.map(e => ({[e]: json[e]}) );
console.log(newjson);
$('#titulo').populate(newjson, {'keys' : true, 'origin' : 'TOP'});
It looks like the populate()
can not populate a form using an array of objects, it fills the form with just one of the elements of the array.
Anyway, I will appreciate any kind of help that you guys may offer to me. Much thanks.
$(document).ready(function(){
$('#IDUnidade').on('change', function(){
$.ajax({
type: 'POST',
data: $(this).attr('name') +'='+ $(this).val(),
dataType: 'JSON',
url: target,
success: function(d) {
for (let i=0; i<d.length; i++) {
$('#titulo').append('<option value="'+d[i].value+'">'+d[i].name+'</option>')
}
}
})
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.