timpone
timpone

Reputation: 19969

how to get specific form FormData

I would like to use the html5 FormData api. Like so:

var formData = new FormData(document.querySelector('form'))

but I have multiple forms. how do I select a specific form like for:

<form accept-charset="UTF-8" action="/timeline_events" class="timeline-event-form timeline_event_form">

?

Upvotes: 0

Views: 3556

Answers (2)

Muhammad Usman
Muhammad Usman

Reputation: 10148

You can use document.querySelectorAll('form'). This will return you list of all the forms. Now you can get data of any form just using index on this node list like

var froms = document.querySelectorAll('form');
var f1Data = new FormData(forms[1]); //To get the data of first form
var f2Data = new FormData(forms[2]);
....

Or you can also add data-attribute to each form and select the required form with that

Something like

<form data-form="form-1">...</form>
<form data-form="form-2">...</form>
<form data-form="form-3">...</form>

Now you can use document.querySelector('form[data-form="form-1"]'); to get the first form and so on

Upvotes: 3

Obsidian Age
Obsidian Age

Reputation: 42324

Simply use a specific selector in your .querySelector().

If you want to only target the form with the class of timeline-event-form, you can combine the element selector form with the class selector .timeline-event-form as:

var formData = new FormData(document.querySelector('form.timeline-event-form'))

Upvotes: 0

Related Questions