Prasad_Joshi Prasad_Joshi - 22 days ago 9
HTML Question

On Refresh, newly added element in array is removed from the array list itself

When ever I add new element in an array, it gets added successfully but when I refresh the browser, the added element gets removed from the list itself. here is my code snippet.

<html>
<label>Enter an New item to add in Stock</label> <br> </br>
<input type="text" name=" itemName" id="addItemInStock><br></br>
<p id="errorMsg"></p>
<button onclick="addToStock()" return="false">Add</button>
<p id="showList"></p>
<select id="showInDropDown">
<option value="" disabled selected style="display: block;">Stock Items</option>
</select>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("showList").innerHTML = fruits;
var newItem = document.getElementById("addItemInStock");

function addToStock(){
if ((newItem.value) === ""){
document.getElementById("errorMsg").innerHTML = "Blank item cannot be added!!";
document.getElementById("errorMsg").style.display = "block";
}
else{
document.getElementById("errorMsg").style.display = "none";
fruits.push(newItem.value);
document.getElementById("showList").innerHTML = fruits;
clearAndShow();
}
var sel = document.getElementById("showInDropDown");
document.getElementById("showInDropDown").innerHTML = "";
for (var i = 0; i < fruits.length; i++)
{
var opt = document.createElement('option');
sel.appendChild(opt);
}
}

function clearAndShow(){
newItem.value = "";
}
</script>

</html>

Answer

Because on refresh, page is repainted. If you need to save the list then you need to use some web storage i.e. localStorage, web storage, etc.

Following is a simple use case of localStorage

Update from

var fruits = ["Banana", "Orange", "Apple", "Mango"];

to

var fruitsfromLS = localStorage.getItem("fruits");
var fruits = fruitsfromLS ? JSON.parse(fruitsfromLS) : ["Banana", "Orange", "Apple", "Mango"];

and update

fruits.push(newItem.value);

to

fruits.push(newItem.value);
localStorage.setItem("fruits", JSON.stringify(fruits));

For reference, localStorage