1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| "use strict";
// modif : 18/04/2024
// création méthode getListeVilles pour plus de cohérence dans le code
// la méthode start devient ainsi plus concise
const App = {
selectVilles: document.getElementById("select-villes"),
inputCode: document.getElementById("input-code"),
formElement: document.querySelector("form"),
resetSelect: function() {
this.selectVilles.options.length = 1;
this.selectVilles.setAttribute("disabled", "disabled");
},
sendDatas: function(e) {
e.preventDefault();
const f = this.formElement;
const output = document.querySelector("output");
// info requête
const reqURL = f.getAttribute("action");
output.textContent = "";
fetch(reqURL, {
method: f.method,
body: new FormData(f)
})
.then((reponse) => reponse.text())
.then(data => {
output.innerHTML = data;
})
/*f.reset();
this.resetSelect();*/
},
updateListeVilles: function(datas) {
// purge sauf 1st
this.selectVilles.options.length = 1;
// on met dans l'ordre
datas.sort((a, b) => a.nom.localeCompare(b.nom));
const list = datas.map((data) => new Option(data.nom, data.nom));
// on ajoute
this.selectVilles.append(...list);
if (datas.length) {
this.selectVilles.removeAttribute("disabled");
this.selectVilles.value = datas[0].nom;
if (datas.length > 1) this.selectVilles.focus();
}
},
getListeVilles: function(e) {
this.resetSelect();
const value = e.target.value;
if (Number(value) && value.length == 5) {
const url = "https://geo.api.gouv.fr/communes?codePostal=" + value;
fetch(url)
.then((reponse) => reponse.json())
.then(data => this.updateListeVilles(data))
}
},
start: function() {
this.resetSelect();
this.formElement.addEventListener("submit",this.sendDatas.bind(this));
this.formElement.addEventListener("reset", this.resetSelect.bind(this));
this.inputCode.addEventListener("input", this.getListeVilles.bind(this));
}
}
App.start(); |
Partager