select the province and the cantons

1

good afternoon

I have the following code that what it tries to do is take the provinces and cantons, but I honestly do not know how to do so that when selecting the province, load the cantons that match the province ID

<html>

    <head>
        <title>Obteniendo las provincias</title>
            <script src="js/jquery.min.js"></script>
        <script>
            $(document).ready(function () {
                    $.ajax({
                        dataType: "json",
                        url: "https://ubicaciones.paginasweb.cr/provincias.json",
                        data: {},
                        success: function (data) {
                            var html = "<select>";
                            for(key in data) {
                                html += "<option value='"+key+"'>"+data[key]+"</option>";
                            }
                            html += "</select";
                            $('#destino').html(html);
                        }
                    });
            })
            </script>

            <script>
            $(document).ready(function () {
                var n= '1';
                    $.ajax({
                        dataType: "json",
                        url: 
                        "https://ubicaciones.paginasweb.cr/provincia/"+n+"/cantones.json",
                        data: {},
                        success: function (data) {
                            var html = "<select>";
                            for(key in data) {
                                html += "<option value='"+key+"'>"+data[key]+"</option>";
                            }
                            html += "</select";
                            $('#canton').html(html);
                        }
                    });

            })
            
            
        </script>


    </head>
      
       <div id="destino" ></div>
 

         <div id="canton"></div>
    </body>
</html>

As you can see in the second function I'm using a variable "var n = 1" in that way, because I'm sending the id of the province, what I need is for that variable to default to the value of the "id = destination" "

I hope you can help me.

Thank you very much for the information and suggestions since I am learning javascript and web services I am a beginner, now what I try to do with the code you gave me is to show me the districts. so I'm doing this:

        $(document).on('change', '#canton > select', function() {
        var provincia = this.value;
        var canton = this.value;
         $.ajax({
             dataType: "json",
             url: "https://ubicaciones.paginasweb.cr/provincia/" + provincia + "/canton/" + canton + "/distritos.json",
             data: {},
             success: function(data) {
                 agregarDistritos(data);
             }
         });

    });

but when I select for example the 8th district of some canton I get an error because it takes the value of the canton also in the province:

jquery.min.js: 4 GET link 404 ()

    
asked by Francisco Araya 09.12.2017 в 19:54
source

1 answer

0

I will give you some advice regarding your code:

  • The ready callback should not be used more than once as this has an impact on performance. This will impact you when you develop applications with a high demand for resources on the side of your user.
  • Each callback ready has its own context. This means that from the first call ready you will not be able to access variables or functions of the second ready and vice versa.
  • You must implement the change function on the list of provinces. So when someone selects a new value, the function change is executed and the call is made to your function that returns the cantons by provinces.
  • Normally it is only necessary to call the function change in this way $('#mi_select').change(function() {}); but as you are creating a new object select for each execution, you should use / hear the event change at the document level , for any select below the target . This is for dynamic objects, that is why I call it this way $(document).on('change', '#destino > select', function() {})
  • I have modified your code and created two variables ( all provinces and cantons of the first two provinces ) for testing and demonstration purposes. You should comment on all blocks marked // INICIO: Comentar al momento de utilizar ajax up to // FIN: Comentar al momento de utilizar ajax and discuss the opposites.
  • $(document).ready(function() {
    
        // INICIO: Comentar al momento de utilizar ajax
        var provincias = {
                "1": "San José",
                "2": "Alajuela",
                "3": "Cartago",
                "4": "Heredia",
                "5": "Guanacaste",
                "6": "Puntarenas",
                "7": "Limón"
                },
            cantones = {'1': {
                "1": "Central",
                "2": "Escazú",
                "3": "Desamparados",
                "4": "Puriscal",
                "5": "Tarrazú",
                "6": "Aserrí",
                "7": "Mora",
                "8": "Goicoechea",
                "9": "Santa Ana",
                "10": "Alajuelita",
                "11": "Vázquez De Coronado",
                "12": "Acosta",
                "13": "Tibás",
                "14": "Moravia",
                "15": "Montes De Oca",
                "16": "Turrubares",
                "17": "Dota",
                "18": "Curridabat",
                "19": "Pérez Zeledón",
                "20": "León Cortés Castro"
            }, '2': {
                "1": "Central",
                "2": "San Ramón",
                "3": "Grecia",
                "4": "San Mateo",
                "5": "Atenas",
                "6": "Naranjo",
                "7": "Palmares",
                "8": "Poás",
                "9": "Orotina",
                "10": "San Carlos",
                "11": "Zarcero",
                "12": "Valverde Vega",
                "13": "Upala",
                "14": "Los Chiles",
                "15": "Guatuso"
            }};
        // FIN: Comentar al momento de utilizar ajax
    
        // INICIO: Descomentar al momento de utilizar ajax
        // $.ajax({
        //     dataType: "json",
        //     data: [],
        //     url: "https://ubicaciones.paginasweb.cr/provincias.json",
        //     type: 'GET',
        //     crossDomain: true,
        //     success: function(data) {
        //         agregarProvincias(data);
        //     }
        // });
        // FIN: Descomentar al momento de utilizar ajax
    
        $(document).on('change', '#destino > select', function() {
            var provincia = this.value;
            // INICIO: Descomentar al momento de utilizar ajax
            // $.ajax({
            //     dataType: "json",
            //     url: "https://ubicaciones.paginasweb.cr/provincia/" + provincia + "/cantones.json",
            //     data: {},
            //     success: function(data) {
            //         agregarCantones(data);
            //     }
            // });
            // FIN: Descomentar al momento de utilizar ajax
    
            // INICIO: Comentar al momento de utilizar ajax
            agregarCantones(cantones[provincia]);
            // FIN: Comentar al momento de utilizar ajax
        });
    
        // INICIO: Comentar al momento de utilizar ajax
        agregarProvincias(provincias);
        // FIN: Comentar al momento de utilizar ajax
    
        function agregarProvincias(data) {
            var html = "<select>";
            for (key in data) {
                html += "<option value='" + key + "'>" + data[key] + "</option>";
            }
            html += "</select";
            $('#destino').html(html);
        }
    
        function agregarCantones(data) {
            var html = "<select>";
            for (key in data) {
                html += "<option value='" + key + "'>" + data[key] + "</option>";
            }
            html += "</select";
            $('#canton').html(html);
        }
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="destino" ></div>
    <div id="canton"></div>
        
    answered by 10.12.2017 / 02:14
    source