+ 2

[SOLVED] HTML5 dynamic datalist possible?

Can datalist items filled remotely to make an autocomplete input component? <form> <input type="text" name="color" list="colors"> <datalist id="colors"> <option value="Red"> <option value="Blue"> <option value="Green"> </ datalist> </form> https://code.sololearn.com/Wt05HMSX85Mg/?ref=app

30th Nov 2020, 4:20 PM
David Ordás
David Ordás - avatar
3 Réponses
+ 2
Possible using Javascript window.onload = () => { let dataList = document.querySelector( "#colors" ); let optionValues = [ "Orange", "Cyan", "Magenta", "Yellow", "Black" ]; // add each element of <optionValues> array for( let optionValue of optionValues ) { let newOption = document.createElement( "option" ); newOption.value = optionValue; dataList.appendChild(newOption); } }
30th Nov 2020, 4:39 PM
Ipang
+ 1
Hey Ipang and I suppouse that source can be a remote call from an API using fetch Great!!!
30th Nov 2020, 10:34 PM
David Ordás
David Ordás - avatar
+ 1
Yes David Ordás I guess it is a viable option, but TBH I haven't studied fetch yet. Look forward for someone's code example. Most welcome 👌
30th Nov 2020, 10:50 PM
Ipang