Search code examples
javascripthtmlgetelementbyidinserthtml

Add array element from form submission


I'm learning JS and how to add array elements. I want to have the info submitted in the form as a new array element and have it displayed it below. Can't find the way to do it using JS. Can someone help? Find below my code so far, which doesn't work:

   <!DOCTYPE html>
    <html>
      <body>
        <form>
          New array element:<br>
          <input id="age" type="text" name="firstname" value="">
          <br>
          <br>
          <input type="submit" value="Submit" onclick="myFunction()">
        </form> 
        <p id="demo"></p>

        <script>
          var fruits = ["Banana", "Mango", "Apple"]
          var newArray = document.getElementById("age").value;
          fruits.push(newArray);
          document.getElementById("demo").innerHTML = fruits;
        </script>
      </body>
    </html>

Thanks!


Solution

  • You are calling myFunction() on a button click but there is no function declaration for myFunction() in <scripts>

       <!DOCTYPE html>
    <html>
    <body>
    
    
    New array element:<br>
    <input id="age" type="text" name="firstname" value="">
    <br>
    <br>
    <input type="button" value="Submit" onclick="myFunction()">
    
    
    <p id="demo"></p>
    
    <script>
        var fruits = ["Banana", "Mango", "Apple"];
    function myFunction(){
    var newArray = document.getElementById("age").value;
    fruits.push(newArray);
    document.getElementById("age").value = "";
    document.getElementById("demo").innerHTML = fruits;
     }
    </script>
    
    </body>
    </html>

    EDIT

    Made fruits array as global, i.e., moved var fruits = ["Banana", "Mango", "Apple"]; outside of the function as per OP's requirements.