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?
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 );
}