Reputation: 91
I am trying to populate a form with a Select element using ajax and Django.
The code I have is the following, but it only shows me one result, when sometimes there are more results.
const cliente = document.querySelector('#selectClienteID')
cliente.addEventListener('change', (event) => {
event.preventDefault();
$.ajax({
type: "POST",
data: $("#addPresupuesto").serialize(),
url: '{% url "systemapp:add_presupuesto" %}',
success: function (data) {
const form_label = '<label for="vehiculo">Seleccionar vehículo</label>'+'<select name="vehiculo" class="form-control" id="vehiculo">'+`<option value="" selected="">Seleccionar vehículo</option>`
for (x in data.cars) {
var car = data.cars[x]
console.log(car['marca'])
const option = `<option value="`+car['id']+`">`+car['marca']+`</option>`
$('#showVehiculos').html(form_label + option);
}
},
error: function () {
console.log('Fail')
},
})
})
From my views I send a list with a dictionary and the values to show:
form = AddPresupuesto()
if request.method == 'POST':
if request.is_ajax():
cliente = Cliente.objects.get(id=request.POST.get('cliente'))
vehiculos = Vehiculo.objects.filter(cliente=cliente)
cars_list = []
for car in vehiculos:
cars = {}
cars['id'] = car.id
cars['marca'] = f'{car.marca} {car.modelo}'
cars_list.append(cars)
return JsonResponse({'cars':cars_list})
but when showing the results in the template only one is shown
It should be two in this case, as shown in the console:
Could someone give me a hand?
regards
Upvotes: 1
Views: 1887
Reputation: 28522
You are using .html()
inside for-loop
so it will override any data inside showVehiculos
.Instead you move that part outside your for-loop
and then use +=
to append new htmls to some variable i.e : options
and then append them to your div
Demo Code :
//just demo data
var data = {
"cars": [{
"1": 12,
"marca": "ac"
}, {
"2": 12,
"marca": "ac2"
}]
}
const form_label = '<label for="vehiculo">Seleccionar vehículo</label>' + '<select name="vehiculo" class="form-control" id="vehiculo">' + `<option value="" selected="">Seleccionar vehículo</option>`
let option = ""; //declare outside
for (x in data.cars) {
var car = data.cars[x]
//append new htmls inside options
option += `<option value="` + car['id'] + `">` + car['marca'] + `</option>`
}
$('#showVehiculos').html(form_label + option); //add all inside div
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showVehiculos">
</div>
Upvotes: 2