About your solution:
It is unnecessary to obtain the amount of inputs that the form has and then iterate over them. Your solution with jQuery can be reduced to:
function getFormData(){
var config = {};
$('input').each(function () {
config[this.name] = this.value;
});
console.log(config);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1> Login </h1>
<form>
<label for"username">Email:</label>
<input name="username" type ="email" value="[email protected]">
<label for="password">Password:</label>
<input name="password" type ="password" value="hello1234">
<button type="button" onclick="getFormData();">Get form data</button>
</form>
You can take advantage of the iteration of the function each
to initialize the object config
, referring to each element using the keyword this
, which in this context refers to the element of iteration.
Without using jQuery:
You can do the same without using jQuery, just with JavaScript through getElementsByTagName () .
For example:
function getFormData(formId){
let formValues = {};
var form1Inputs = document.forms[formId].getElementsByTagName("input");
for(let i=0; i<form1Inputs.length; i++){
formValues[form1Inputs[i].name]=form1Inputs[i].value;
}
console.log(formValues);
}
<h1> Login </h1>
<form id="form1">
<label for"username">Email:</label>
<input name="username" type ="email" value="[email protected]">
<label for="password">Password:</label>
<input name="password" type ="password" value="hello1234">
<button type="button" onclick="getFormData('form1');">Get form data</button>
</form>
Other alternatives with jQuery:
- using serializeArray () create an array from the form elements that have
name
and are not found disabled
(see as password
is not included in the following example)
- using serialize () , which returns a string.
function getFormData(formId){
console.log($('#'+formId).serializeArray());
console.log($('#'+formId).serialize());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1> Login </h1>
<form id="form1">
<label for"username">Email:</label>
<input name="username" type ="email" value="[email protected]">
<label for="password">Password:</label>
<input name="password" type ="password" value="hello1234" disabled>
<button type="button" onclick="getFormData('form1');">Get form data</button>
</form>