0 votes

How can I load a combobox depending on the selection of another combobox with javascript?

I need through javascript that the commune is selected in the combobox depending on the region that I select in the previous combobox In my models.py I have it as follows:

 class Region(models.Model):
nro_region = models.IntegerField(unique=True, verbose_name="Nro. Región")
nombre = models.CharField(max_length=60)

class Comuna(models.Model):
nombre = models.CharField(max_length=60)
region = models.ForeignKey(Region, on_delete=models.CASCADE)

So in my template I have 2 combobox, but depending on the region that I select, I have to load the communes that belong to that region. How can I get it with javascript? Thanks a lot.

0voto

Euler Points 139

For your question we have to use onchange

HTML:

 <select id="comboA" onchange="getComboA(this)">
    <option value="">Select combo</option>
    <option value="Value1">Text1</option>
    <option value="Value2">Text2</option>
    <option value="Value3">Text3</option>
    </select>



 <select id="comboB">

    </select>

javascript:

 function getComboA(selectObject) {

    // aqui dependera de donde obtienes los datos para ingresar las opciones de tu combo, puede ser una invocacion `ajax`
    var option = document.createElement("option");
    option.text = "Text";
    option.value = "myvalue";
    var select = document.getElementById("comboB");
    select.appendChild(option); 
}

I hope it helps you, Greetings.

0voto

Kevdev Points 16

You can do something like this, where you use the change event to consult the information you handle in your models through ajax. Every time you change region, a request will be made and the options of your commune combo will be changed. I see that you use MVC so it would be to send the info to your controller

  $("#micombo").change(function(){

    var region =$("#micombo").val(); 
        var connect, form, response, result;

        form = "region="+region; //informacion que enviaras a tu .py 
        connect = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
        connect.onreadystatechange = function() {
            if(connect.readyState == 4 && connect.status == 200) {                  
                var datos = JSON.parse(connect.responseText);
                //luego de la respuesta del servidor recorreras todas las comunas para llenar el segundo combo
                $.each( datos, function( key, value ) {

                    $("#miselect").append("<option value ='"+value.id+"'>"+value.descripcion+"</option>");
                });
            }
        }

        connect.open('GET','miPythonController.py',true);
        connect.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        connect.send(form);
});

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X