user7988893
user7988893

Reputation:

Is there a simpler way to get formData with pure js?

My html structure is as below,a table nested in form, some info in input or option in select will send via ajax.

<form>
<table>
    <tr>
        <td>date</td>
        <td><input class="data" type='text' name="date"></td>
    </tr>
    <tr>
        <td>type</td>
        <td>
        <select id="type" name="type">
            <option value="word">word</option>
            <option value="phase">phrase</option>
            <option value="sentence">sentence</option>
            <option value="grammar">grammar</option>
        </select>
    </td>
    </tr>
    <tr>
        <td>content</td>
        <td><textarea  class="data" name='content' cols="80" rows="8"></textarea></td>
    </tr>
    <tr>
        <td>meaning</td>
        <td><textarea  class="data" name='meaning' cols="80" rows="8"></textarea></td>
    </tr>
    <tr>
        <td>source</td>
        <td><input class="data" type="text" name="source"></td>
    </tr>
    <tr>
        <td colspan="2"><input type="button" value="submit" id="submit"></td>
    </tr>
</table>
</form>

I get the formData with below code, it is verified that all data in the form can get.

var elements = document.getElementsByClassName("data");
var formData = new FormData(); 

for(var i = 0; i < elements.length; i++)
{
    formData.append(elements[i].name, elements[i].value);
}

var mySelect = document.getElementById("type");
var index = mySelect.selectedIndex;
var svalue = mySelect.options[index].value;
var sname = "type";
formDate.append(sname,svalue);

It is a bit long lines here, i want more small js code.
Is ther more simple way to get formData with pure js ,instead of jQuery?

Upvotes: 3

Views: 6613

Answers (4)

Sebas Rossi
Sebas Rossi

Reputation: 39

You can use the get() method of formData to retrieve any value of the form inputs.

formData.get('input_name');

or

formData.append('new_element');
var newElement = formData.get('new_element');

From Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/API/FormData/get

Upvotes: 0

this code will return object with all keys and values that we have in the form

var formData = Object.fromEntries(new FormData(document.querySelector('form')).entries());

result:

{ key_1: value_1, key_2: value_2, key_3: value_3, ... }

Upvotes: 1

Edwin Dijas Chiwona
Edwin Dijas Chiwona

Reputation: 620

This should work for all input Element and Select element. if you have multiple forms, get form by Id. Thanks. If any errors let me know. typing from mobile.

var elements = document.getElementsByTagName("form");

var formData = new FormData(); 
var ipts = elements.querySelector('input, select');
for(var ipt of ipts)
{
    formData.append( ipt.name, ipt.value );
}

Upvotes: 0

Quentin
Quentin

Reputation: 943650

Just pass the whole form to the object.

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

Upvotes: 8

Related Questions