Search code examples
javascripthtmlcssclientlocal-storage

Get value from input and store it to the object Javascript


How I can get value from input and store it to the object? When button is clicked value from the input - should to be stored in the object. Thank you a lot in advance

var testObject = { 'name': nameOfbook.value, 
                    'author': nameOfauthor.value, 
                    'year': year.value
                };
console.log(testObject);
    <input type="text" id="nameOfbook" required="" placeholder="Book name" />
    <input type="text" id="nameOfauthor" required="" placeholder="Athor name" />
    <input type="text" id="year" required="" placeholder="Add year" />

   <button id="addder" type="button">StoreEmail</button>


Solution

  • Here's a working JSfiddle for you.

    The relevant JS code is here. Using the id tags on your html elements, I got all of the elements and stored them into variables. Next, I added an event listener on your button, and on click, I push the relevant value of each element into your testObject.

    var testObject = [];
    
    const button = document.getElementById("addder");
    
    const name = document.getElementById("nameOfbook");
    const author = document.getElementById("nameOfauthor");
    const year = document.getElementById("year");
    
    
    button.addEventListener("click", function() {
      testObject.push({
        name: name.value,
        author: author.value,
        year: year.value
      })
      console.log(testObject)
    })
    

    https://jsfiddle.net/991jqomq/