Create and Send Interactive Form Fields using JavaScript

After a user takes an action, I dynamically generate this form using 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 function editBookData() is as follows:

function editBookData(data) {
    console.log(data)
   //Additional tasks here
}

I am seeking guidance on how to prevent the default submission behavior of the form and pass the form data so that it can be accessed within the editBookData() function.

Please provide solutions without using JQuery. Thank you in advance.

Answer №1

To prevent the form from reloading, you can utilize the preventDefault() method. Additionally, to retrieve the input text values of the form, you can make use of the querySelector method within your function.

Check out this Live Demo: (No jQuery)

function editBookData(e) {
  e.preventDefault() //prevents default behavior 
  //retrieve input values
  let isbn = document.querySelector('input[name="isbn"]').value
  let book = document.querySelector('input[name="book"]').value
  console.log(isbn, book)
  //Perform additional tasks with the obtained 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>

Answer №2

Prevent form submission by using event.preventDefault() and dynamically generate a form using the FormData Web API.

Learn more about Event.preventDefault method
Explore the FormData API on MDN

function handleFormData(event) {
  event.preventDefault();
  let formDataElement = document.getElementById('formData');
  let formData = new FormData(formDataElement);
  for (data of formData.values()) {
    console.log(data);
  }
  // .... other actions to perform
}

     
<form id="formData" onsubmit="handleFormData(event)">
      <input type="text" name="user" placeholder="Username" required />
      <input type="email" name="email" placeholder="Email..." required />
      <button class="btn">Submit</button>
</form>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The system encountered an error while attempting to access the property "getChild" of an unspecified object

I am currently developing a react application and encountering an issue when trying to call a function from the render method. The function I'm trying to call utilizes the getChild method, but I keep receiving an error stating "cannot read property &a ...

Expansive menu that stretches the full height of the webpage

I'm having difficulty making my side spry menu extend the full length of the webpage. I tried using this code: $("nav").css({ "height" : $("nav").height() }); but it still isn't working as expected. I just want the grey color, like ...

Is there a way to upload a file using express/multer without triggering a redirect?

Note: Despite coming across this post, I couldn't find it helpful. Other related posts were focused on angular/react, which are not relevant to my current project. I have implemented a file upload feature that should provide a response indicating whe ...

Executing axios within a JavaScript function without relying on global variables

I am currently exploring the usage of axios (https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.0/axios.js) in a function to communicate with my backend and retrieve data. The snippet of code provided is functional. Instead of relying on a global variable ...

dealing with errors coming from a child asynchronous callback function

function main(){ try { subCallbackFunction(1,(err,res) =>{ if(err){ throw Error(err); } }) } catch (e) { /// Handling error from subCallbackFunction inside this catch block ////// conso ...

Understanding the time complexity of Object.entries()

Is the complexity of Object.entries() in JavaScript known? According to information from this question, it seems like it could possibly be O(n) if implemented by collecting keys and values as arrays and then combining them together? ...

How can we prevent checkbox and radio buttons from being triggered by accidental taps on the surrounding area on touch-responsive devices?

On touch screen responsive devices, there seems to be an issue where clicking outside the checkbox or radio button (within about 8px) causes the checkbox or radio button to toggle. This problem only occurs on responsive touch devices and works fine on desk ...

Guide on using JavaScript to automatically scroll a HTML page to the top on any mobile browser

Can JavaScript be utilized to smoothly scroll an HTML page to the top? I am looking to achieve this with a stylish animation that functions correctly on all mobile browsers. jQuery is the library I am using on this particular page. Thank you, ...

Positioning pop-up windows using Javascript and CSS techniques

In my web application, there is a search field that allows users to enter tags for searching. The window should pop up directly below the search field as shown in this image: Image I am trying to figure out how the window positioning is actually d ...

Double invocation of useEffect causing issues in a TypeScript app built with Next.js

My useEffect function is set up with brackets as shown below: useEffect(() => { console.log('hello') getTransactions() }, []) Surprisingly, when I run my app, it logs "hello" twice in the console. Any thoughts on why this might be ...

Having difficulty deciphering JWE Token using Python jwcrypt and NodeJS jose interaction

I am facing an issue with decrypting a JWE Token that was created using the jwcrypt library in Python and trying to decrypt it using the jose library in JavaScript. I have set up the A256KW and A256CBC-HS512 algorithms on both libraries and also provided ...

Customize image using JavaScript or PHP online

Hello everyone, I am in search of a script, library, or framework that allows me to edit pictures similar to the functionality found on this link: door1 door2 door3 What I need is the ability to change the image and return it to the user. For example, if ...

The ngx-mat-intl-tel-input plugin is experiencing issues with functionality within the Angular 17 framework

I am currently using Angular 17 and here are the specific Versions/Details: Angular CLI: 17.3.8 Node: 18.20.2 Package Manager: npm 10.5.0 OS: linux x64 Angular: 17.3.12 My goal is to import the ngx-intl-tel-input library in order to validate phone numbers ...

What's the best way to pinpoint the value of a heading tag?

Is there a way to target the value of an h2 tag, similar to how you would with an input field? const [text, setText] = useState("") <input type="text" onChange={(e) => setText(e.target.value)} /> I attempted <h2 onChange={(e) => setCheck(e ...

Show informational pop-up when hovering over selected option

My goal is to create an information box that appears when a user hovers over a select option. For example: <select id = "sel"> <option value="sick leave">Sick leave</option> <option value="urgent leave">Urgent lea ...

Reading an XML file to locate items nested within the same bracket

Within my JavaScript function, I am utilizing the following code to extract data from an XML file: var title = $(this).children('Title').text(); This snippet of code successfully retrieves the content under the <Title> tags: <Title> ...

The issue with viewing next/image properly only occurs on desktops using a responsive layout. I would like for the image

<Image src={APIImagePath} alt={t("common:tokens")} layout="fill" className={styles.img} /> Showing on a desktop screen: https://i.stack.imgur.com/gT2ZF.png Viewing on a tablet: https://i.stack.imgur.com/yeABR.png ...

Just finished the "Modern React with Redux" Udemy course and encountering some peculiar problems. Any assistance in solving them would be greatly appreciated!

While following the lectures, I made the decision to completely remove the "src" folder. To my surprise, even after refreshing the browser on the "localhost:8080" page, the content "Hello There!!!" from the index.js file remained visible. This was quite st ...

verify whether the image source has been altered

There is an img tag displaying the user's avatar. When they click a button to edit the image and choose a new one, the src attribute of the img changes to the new image src. How can I detect when the src changes? Below is the code for the button tha ...

Focus on selecting each label within a table using JavaScript

In my current setup, I am attempting to customize radio buttons and checkboxes. Array.from(document.querySelectorAll("tr")).forEach((tr,index)=>{ var mark=document.createElement("span"); Array.from(tr.querySelectorAll("input")).forEach((inp,index ...