Prasad_Joshi Prasad_Joshi - 9 months ago 41
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.

<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>

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";
document.getElementById("errorMsg").style.display = "none";
document.getElementById("showList").innerHTML = fruits;
var sel = document.getElementById("showInDropDown");
document.getElementById("showInDropDown").innerHTML = "";
for (var i = 0; i < fruits.length; i++)
var opt = document.createElement('option');

function clearAndShow(){
newItem.value = "";


Answer Source

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"];


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

and update



localStorage.setItem("fruits", JSON.stringify(fruits));

For reference, localStorage