Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

javascript - Populate SELECT options with Ajax and Django

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

enter image description here

It should be two in this case, as shown in the console:

enter image description here

Could someone give me a hand?

regards


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...