samedi 25 juin 2016

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!

Aucun commentaire:

Enregistrer un commentaire