I want to create a form with two fields. One is the starting station and the other is the ending station. The stations are stored in a JSON file {[],[],[]} This json file is about 400KB in size. I want to initialise the stations only once and use them for both input fields. But I can't do that. So I rewrote it so that it loads the JSON as soon as you focus on an input field. Which is pretty stupid. I would be really happy about help. This is my current structure:
app.js
// load own suggestion script
import suggestion from './suggestion';
document.getElementById('from').addEventListener('focus', function() {
suggestion.start('from')
});
document.getElementById('to').addEventListener('focus', function() {
suggestion.start('to')
});
suggestion.js
export default {
stations: [],
formSelector: '',
url: 'http://localhost:8090/api.php',
getData() {
fetch(this.url)
.then(res => res.json())
.then(data => {
// call the autocomplete function and pass the stationData
this.autocomplete(document.getElementById(this.formSelector), data)
})
.catch(err => {
console.log(err)
});
},
autocomplete(inp, arr) {
// some code ... this code fetch the input value and iterate the stations object and create a suggestionlist. I have shortened it for this question.
},
start(selector) {
this.formSelector = selector;
this.getData();
}
}
html
<span>from</span>
<input id="from" type="text" placeholder="Station from">
<span>to</span>
<input id="to" type="text" placeholder="Station to">
How is the following?
Is it what you want to do?
getData() {
if( this.stations ) {
this.autocomplete(document.getElementById(this.formSelector), this.stations);
} else {
fetch(this.url)
.then(res => res.json())
.then(data => {
// call the autocomplete function and pass the stationData
this.stations = data;
this.autocomplete(document.getElementById(this.formSelector), this.stations);
})
.catch(err => {
console.log(err)
});
}
},