简体   繁体   中英

Submit Dynamically Generated From in JavaScript

I have the following form generated dynamically from JavaScript based on user's action:

<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:

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?

No Jquery please. 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

Live Demo: (No 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 reference
FormData API on MDN

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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