繁体   English   中英

从输入中获取值并将其存储到对象 Javascript

[英]Get value from input and store it to the object Javascript

我如何从输入中获取价值并将其存储到对象中? 当单击按钮时,输入中的值 - 应该存储在对象中。 非常感谢你提前

 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>

这是一个适合您的工作 JSfiddle。

相关的JS代码在这里。 使用 html 元素上的id标签,我得到了所有元素并将它们存储到变量中。 接下来,我在您的按钮上添加了一个事件侦听器,并在单击时将每个元素的相关value推送到您的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/

我是这样做的

HTML: 

 <form id="new-post">
            <label for="post-title">Title:</label>
            <input id="post-title" type="text" />
            <label for="post-body">Body:</label>
            <textarea id="post-body"></textarea>
            <button>Post</button>
  </form>
JS: 

document.getElementById("new-post").addEventListener("submit", function(e) {
    e.preventDefault()
    const postTitle = document.getElementById("post-title").value
    const postBody = document.getElementById("post-body").value
    const data = {
        title: postTitle,
        body: postBody
    }
    console.log(data)
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM