Jiang Lan Jiang Lan - 9 months ago 25
HTML Question

How to set the input value to be a object's property's value in javascript

I want to set the input value to be a object's property's value,
here is the code in jsfiddle,

I also put the code here:

html

<div id="contenu"></div>


js

// create the button
var contenu = document.getElementById("contenu");
var btn = document.createElement("button");
btn.textContent = "add";
contenu.appendChild(btn);

// click the button to create 2 inputs and submit
btn.addEventListener("click", function(){
// create 2 inputs and submit
var name = document.createElement("input");
name.placeholder = "enter a name";
var age = document.createElement("input");
age.placeholder = "enter the age";
var submit = document.createElement("input");
submit.type = "submit";
submit.value = "submit";
var form = document.createElement("form");
form.method = "post";
form.appendChild(name);
form.appendChild(age);
form.appendChild(submit);
contenu.appendChild(form);

// create a new empty table
var newTable = [];
var newObject = {};
newObject.name = name.value;//"Tom" will work
newObject.age = age.value;//20 will work
newTable.push(newObject);

// submit the form to show the input value in html
form.addEventListener("submit", function(e){
newTable.forEach(function(table){
e.preventDefault();
var pElt = document.createElement("p");
pElt.innerHTML = table.name + " " + table.age;
contenu.appendChild(pElt);
});
});
});


Objective: click the "add" button to show 2 inputs and the "submit" button, enter the name and the age, then click "submit" to show them in the
div
, I put the input's value as the property's value of the object,
newObject.name = name.value;
and
newObject.age = age.value;
but it dosen't work, thanks for your help!

Answer

I fixed your fiddle, you can check it out here:

https://jsfiddle.net/o08mua1y/

    form.addEventListener("submit", function(e){
        newObject.name = name.value;//"Tom" will work
        newObject.age = age.value;//20 will work
        newTable.forEach(function(table){
            e.preventDefault();
            var pElt = document.createElement("p");
            pElt.innerHTML = table.name + " " + table.age;  
            contenu.appendChild(pElt);
        });   
    });

The issue is that you are trying to set the value of the name, and age field in the listener that creates your input fields, not in the listener that fires on submission of the inputs. If you set those values inside the submit listener, before the forEach loop the values will be set, and be displayed in your HTML as intended