How to create link inside combo box?

Asked

Viewed 93 times

0

I have the following code that generates me a combo box state and city. How do I when clicking on the city redirect me to the city’s page for example that city? Thank you

<script type="text/javascript"> 

    $(document).ready(function () {

        $.getJSON('estados_cidades.json', function (data) {
            var items = [];
            var options = '<option value="">Escolha um Estado</option>';    
            $.each(data, function (key, val) {
                options += '<option value="' + val.nome + '">' + val.nome + '</option>';
            });                 
            $("#estados").html(options);                

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

                var options_cidades = '';
                var str = "";                   

                $("#estados option:selected").each(function () {
                    str += $(this).text();
                });

                $.each(data, function (key, val) {
                    if(val.nome == str) {                           
                        $.each(val.cidades, function (key_city, val_city) {
                            options_cidades += '<option value="' + val_city + '">' + val_city + '</option>';
                        });                         
                    }
                });
                $("#cidades").html(options_cidades);

            }).change();        

        });

    });

</script>       

1 answer

0

Hello,

To do this just create a function by clicking on any option in the list of cities that redirects the user to the right site. See:

$("#cidades").change(function(){
    var cidade = $(this).val();
    var link = ""; 

    switch(cidade){
        case "Rio de Janeiro":
            link = "http://www.rio.rj.gov.br/";
            break;

        case "Sao Paulo":
            link = "http://www.capital.sp.gov.br/";
            break;
    }

    window.location.href = link;
});

I hope I helped, hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.