Error when picking up JSON elements

1

Talk to people, blz? I'm having a problem when receiving the JSON response from Ajax, I can not populate all the states in the select. Although it is inside a for it only takes the last element, ie it runs through all states but only stores the last one ... If anyone knows how to proceed with the script, I thank you!

  

If it were in JQuery I would use .html () to assign the value, but in pure JS?

     
    

select populate only with Tocantins the last element

         
      

In my case the file states-cities.json is local

             
        

LINK states-cities.json link

      
    
  
     

Thank you!

ajax

(function(){
    'use strict';

    var ajax = new XMLHttpRequest();

    var $estado = document.querySelector('[data-js="estado"]');

    ajax.open('GET', 'json/estados-cidades.json', true);
    ajax.send(null);

    var options = "<option value=''>selecione o seu estado</option>";
    $estado.innerHTML = options;

    ajax.addEventListener('readystatechange', function(){

        if(ajax.readyState === 4 && ajax.status === 200){
            var data = JSON.parse(ajax.responseText);

            for(var i = 0; i < data.estados.length; i++){
                options = '<option value='${data.estados[i]["sigla"]}'>${data.estados[i]["nome"]}</option>';

                //$estado.appendChild(options); também nao funciona
                $estado.innerHTML = options;   
            }

        }

    }, false);



})();
    
asked by anonymous 27.10.2017 / 21:58

2 answers

1

You are overwriting content every time you call

$estado.innerHTML = options;

Put the content in a variable and then apply it to HTML

(function(){
    'use strict';

var ajax = new XMLHttpRequest();

var $estado = document.querySelector('[data-js="estado"]');

ajax.open('GET', 'json/estados-cidades.json', true);
ajax.send(null);

var options = "<option value=''>selecione o seu estado</option>";
$estado.innerHTML = options;

ajax.addEventListener('readystatechange', function(){

    if(ajax.readyState === 4 && ajax.status === 200){
        var data = JSON.parse(ajax.responseText);

        for(var i = 0; i < data.estados.length; i++){
            options = options + '<option value='${data.estados[i]["sigla"]}'>${data.estados[i]["nome"]}</option>';                

        }
        $estado.innerHTML = options;   

    }

}, false);

})();
    
27.10.2017 / 22:03
0

Really inside the for I was not getting the options variable itself I did not notice that I did not receive the same options + = ....

Thank you Luciano Marqueto, thanks!

    
27.10.2017 / 22:12