简体   繁体   English

提交动态生成自 JavaScript

[英]Submit Dynamically Generated From in JavaScript

I have the following form generated dynamically from JavaScript based on user's action:我根据用户的操作从 JavaScript 动态生成以下表单:

<form id="editBookForm" onsubmit="editBookData()">
   <input type="text" name="isbn" placeholder="ISBN"  required />
   <input type="text" name="book" placeholder="Book..."  required />
   <button class ="btn">Update!</button>
</form>

The editBookData function is: editBookData function 是:

function editBookData(data) {
    console.log(data)
   //Some other work
}

How can I prevent default submission behavior and pass the form data so that I can access the form data in the editBookData() function?如何防止默认提交行为并传递表单数据,以便我可以访问editBookData() function 中的表单数据?

No Jquery please.没有 Jquery 请。 Thank you in Advance.先感谢您。

You can use preventDefault() method to the stop form from reloading and use querySelector method to get the form input text values in your function您可以使用preventDefault()方法停止重新加载form ,并使用querySelector方法获取 function 中的表单输入文本values

Live Demo: (No jQuery)现场演示:(无 jQuery)

 function editBookData(e) { e.preventDefault() //prevent default behaviour //get input value let isbn = document.querySelector('input[name="isbn"]').value let book = document.querySelector('input[name="book"]').value console.log(isbn, book) //Do Some other work with values }
 <form id="editBookForm" onsubmit="editBookData(event)"> <input type="text" name="isbn" placeholder="ISBN" required /> <input type="text" name="book" placeholder="Book..." required /> <button class="btn">Update!</button> </form>

Use event.preventDefault() to prevent the submission of the form and use the FormData Web API to generating a form dynamically.使用event.preventDefault()来阻止提交表单,并使用FormData Web API 动态生成表单。

Event.preventDefault reference Event.preventDefault 参考
FormData API on MDN MDN 上的 FormData API

 function editBookData(event) { event.preventDefault(); let editBookForm = document.getElementById('editBookForm'); let formData = new FormData(editBookForm); for (item of formData.values()) { console.log(item); } //.... other things to do }
 <form id="editBookForm" onsubmit="editBookData(event)"> <input type="text" name="isbn" placeholder="ISBN" required /> <input type="text" name="book" placeholder="Book..." required /> <button class="btn">Update!</button> </form>

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

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