Submit Dynamically Generated From in JavaScript

Viewed 58

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.

2 Answers

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>

Related