1

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>
Dipu Raj
  • 1,784
  • 4
  • 29
  • 37
Prasad_Joshi
  • 642
  • 3
  • 13
  • 34

3 Answers3

2

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

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

If you want to retain the values even after the refresh of a web browser use local storage. https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage

Ashok kumar
  • 544
  • 1
  • 5
  • 21
0

That is because value added in array are session specific, so they are deleted on page load. You can you LOCAL STORAGE to fix this. Refer this link: Storing Objects in HTML5 localStorage

Community
  • 1
  • 1
Tejas
  • 239
  • 1
  • 2
  • 6