Search code examples
javascriptarraysformsobjectinput

How to push a new object to an array of objects using a from input in JavaScript?


As the title says, i have an array of objects:

let bookObjects = [
        {
            title: "Defender With A Goal",
        },
        {
            title: "Pirate Of The End",
        },
        {
            title: "Kings Of Rainbows",
        },
        {
            title: "Traitors Of The Forsaken",
        },
        {
            title: "Enemies And Invaders",
        },
    ];

And i have a form:

<form name="myform" action="" method="GET">
    Add new element to the table: <br>
    <input type="text" name="inputbox" value="">
    <p>
        <input type="button" name="button" value="Submit" onClick="addNewObjet(this.form)">
    </p>
</form>

And a function that should add a new object:

addNewObjet = (form) => {
        let newTitle = form.inputbox.value; //inputbox is the name of the input

        bookObjects.push(
            {
                title: newTitle,
            },
        );
    }

If i try to push into bookObjects without the input it does work, but with the form it doesn't.


Solution

  • let bookObjects = [
            {
                title: "Defender With A Goal",
            },
            {
                title: "Pirate Of The End",
            },
            {
                title: "Kings Of Rainbows",
            },
            {
                title: "Traitors Of The Forsaken",
            },
            {
                title: "Enemies And Invaders",
            },
        ];
        
        addNewObjet = (form) => {
            let newTitle = form.inputbox.value; //inputbox is the name of the input
    
            bookObjects.push(
                {
                    title: newTitle,
                },
            );
            
          var table = document.getElementById("tbl");
          table.innerHTML = "";
          
          bookObjects.forEach(b => {
          var row = table.insertRow(0);
    
           
          var cell1 = row.insertCell(0);
          var cell2 = row.insertCell(1);
    
           
          cell1.innerHTML = b.title;
          })
    
         
          
       
        }
            
          var table = document.getElementById("tbl");
    
         
          var row = table.insertRow(0);
    
           
          var cell1 = row.insertCell(0);
          var cell2 = row.insertCell(1);
    
           
          cell1.innerHTML = newTitle;
       
        }
    

    This puts the input into a table and this seems to work.