1

When I try to run this script, it updates my array for a second, but it seems that after the function runs, the document returns to normal.

What's the best way to solve this problem?

<p id="demo"></p>

<form>
    <input type="submit" onclick="add_value()"/>
</form>


<script>    
    var array = ["1", "2", "3"];
    document.getElementById("demo").innerHTML = array[3];

    function add_value() {
        array.push("69");
        document.getElementById("demo").innerHTML = array[3];
        document.getElementById("demo2").innerHTML = array[3];
    }
</script>
Emma
  • 27,428
  • 11
  • 44
  • 69
JohnSeuss
  • 51
  • 9
  • 1
    Well, outside of your function, `array[3]` doesn't exist, so there would be an error. – Jack Bashford Feb 02 '19 at 00:47
  • 1
    @JackBashford It would evaluate to `undefined`, not be an error iirc. – Carcigenicate Feb 02 '19 at 00:48
  • What do you mean by "but it seems that after the function runs, the document returns to normal"? What is the exact behavior you're seeing in relation to before and after the button press? – Carcigenicate Feb 02 '19 at 00:50
  • 1
    As explained above `array[3]` does not exist. Array index will start from **0** so `array[2]` will return the third item in the `array` and `array[0]` will return the first item in the `array` – NewToJS Feb 02 '19 at 00:51
  • 1
    @JackBashford how would i make array[3] exist outside the function? I want to push a button to add an entry to the array and update the demo paragraph – JohnSeuss Feb 02 '19 at 00:52
  • 1
    Possible duplicate of [How do I make an HTML button not reload the page](https://stackoverflow.com/questions/1878264/how-do-i-make-an-html-button-not-reload-the-page) – NineBerry Feb 02 '19 at 01:06

1 Answers1

4

Because you have an input of type submit, the browser reloads the page after you press the button.

Instead use

<input type="button"
NineBerry
  • 26,306
  • 3
  • 62
  • 93