I am writing a website, one section of the website is for users to either select an existing TesterName or enter a new one.
var curTester;
function SetTesterName() {
var Value = document.getElementById("testerNameInput").value;
if (!Value) return;
if ( $("#testerNameList").find("option[value='" + Value + "']").length == 0 ) {
var option = document.createElement("option");
option.value = Value;
document.getElementById('testerNameList').appendChild(option);
alert('New tester name added');
}
curTester = Value;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="testerNameInput" >Tester Name</label>
<input id = "testerNameInput" list = "testerNameList" name = "testerNameInput" type = "text" style="width: 70%"/>
<datalist id="testerNameList">
<option value="Name1">
<option value="Name2">
<option value="Name3">
</datalist>
<button onclick="SetTesterName()">Submit</button>
This 2 pieces of code work fine, but when I reload the webpage and look into the datalist, the new appended option is missing. What should I do?
if you want to solve only frontend you can use localStorage for this problem.
If you want users to see what has been added by other users, you need a backend to handle database operations.
i edit your snippet. you can check here
var curTester;
var testerNameList = localStorage.getItem('testerNameList');
function SetTesterName() {
var Value = $('#testerNameInput').val()
if (!Value) return;
if ( $("#testerNameList").find("option[value='" + Value + "']").length == 0 ) {
// var option = document.createElement("option");
// option.value = Value;
// document.getElementById('testerNameList').appendChild(option);
// you can use short way like below
$('#testerNameList').append($(`<option value="` + Value + `"></option>`))
testerNameList = localStorage.getItem('testerNameList');
if(!testerNameList){ // localStorage empty
localStorage.setItem('testerNameList', JSON.stringify([Value]));
}else{
let arr = JSON.parse(testerNameList)
arr.push(Value)
console.log(arr)
localStorage.setItem('testerNameList', JSON.stringify(arr));
}
alert('New tester name added');
}
curTester = Value;
}
// When the page is ready it adds the elements found in the local storage.
// Shorthand for $( document ).ready()
$(function() {
if(testerNameList != null){
JSON.parse(testerNameList).forEach(x => {
$('#testerNameList').append($(`<option value="` + x + `"></option>`))
})
}
});