2

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.

1
  • Take the event as a parameter to your function and call .preventDefault() on it? Commented Sep 2, 2020 at 1:03

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @AlwaysHelping. Appreciate it. :)
@hadira2145 Glad to help. Happy coding.
1

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>

2 Comments

Not ideal !! How would you differentiate which text value is what if you use formData here ? Because item will show both values here. No point using formData here if there are two values only.
FormDatay has other methods like FormData.get(name). You can use it to get each input value by its name attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.