1
Speak guys, blz? I have a problem when it comes to receiving the answer in JSON from Ajax, I can not popular all states in select. Although it is inside of a being it takes only the last element, ie it goes through all the states but only stores the last... If anyone knows how to proceed with the script, I’d appreciate it!
If it were in Jquery it would use . html() to assign the value, but in pure JS?
select populates only with Tocantins the last element
In my case the.json states file is local
LINK states-cities.json https://gist.github.com/lucashort7/313bec7d4a8b82472ac19993681d71c2
Thank you!
(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);
})();
Hi Igor! If Luciano’s answer solved the problem you can click to mark as accepted,
– Sergio