So, let's say I have an HTML form like this:
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
And I want to get a JavaScript array that matches the values of real. For example:
// If there was a sweet function for this...
var people = getFormDataByInputName( 'people' );
// Value of `people` is...
// [
// {
// 'first_name' : 'John',
// 'last_name' : 'Doe'
// },
// {
// 'first_name' : 'Jane',
// 'last_name' : 'Smith'
// }
// ]
Is there any easy way of doing that for just a specific form item (in this case, people)? Or would I have to serialize the entire form an then just extract the element I want?
I also thought of potentially using the following approach:
var formData = new FormData( document.querySelector( '#myForm' ) );
var people = formData.get( 'people' );
But that doesn't appear to work; people is just null after that.
You could do this with plain js using reduce method and return each person is one object.
const form = document.querySelectorAll('#myForm input');
const data = [...form].reduce(function(r, e) {
const [i, prop] = e.name.split(/\[(.*?)\]/g).slice(1).filter(Boolean)
if (!r[i]) r[i] = {}
r[i][prop] = e.value
return r;
}, [])
console.log(data)
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
function getObject(name, key) {
if(key.includes(name)) {
var splitStr = key.split(/\[|\]/g);
return {
index: splitStr[1],
key: splitStr[3],
}
}
return null;
}
function getFormDataByInputName(name) {
var formData = new FormData( document.querySelector('#myForm'));
var results = [];
for (var key of formData.keys()) {
var obj = getObject(name, key);
if (obj) {
if (results[obj.index]) results[obj.index][obj.key] = formData.get(key);
else results[obj.index] = { [obj.key]: formData.get(key) };
}
}
return results;
}
var people = getFormDataByInputName('people');
console.log(people);
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
Your code won't work because to HTML/JS name is just a string that it sends to the server when the form is submitted (the name in the name/value pairs). You might think it is arrays, but HTML/JS doesn't.
So no one-liner to get the job done. Try this: In your HTML, add <div class="name"> ...
(UPDATE: thanks for the idea, #Nenad, I've never tried one of these snippets)
var people = [];
$('.name').each(function() {
people.push({
first_name: $('input:nth-child(1)', this).val(),
last_name: $('input:nth-child(2)', this).val()
});
});
console.log(people);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="text" name="dummy">
<div class="name">
<input type="text" value="John">
<input type="text" value="Doe">
</div>
<div class="name">
<input type="text" value="Jane">
<input type="text" value="Smith">
</div>
</form>
Use CSS attribute prefix selector, such as
form.querySelectorAll('[name^="people[]"]')
You can use a for-loop to get all peoples, as such
const MAX_PEOPLES = 2;
const list = [];
for (i = 0; i <= MAX_PEOPLES; i++) {
const eles = form.querySelectorAll(`[name^="people[${i}]`);
if (eles.length !== 2)
break;
list.push({
first_name: eles[0].value,
last_name: eles[1].value
});
}
that yields
[
{
"first_name":"John",
"last_name":"Doe"
},
{
"first_name":"Jane",
"last_name":"Smith"
}
]
Related
I am trying to write a function in jQuery.
var arr1 = ["Jcob", "Pete", "Fin", "John"];
var str = $("#fname").val();
if (jQuery.inArray(str, arr1))
$("#lname").text("Bob");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
Please check my fiddle here
What it will do it the user will give the value in the first input box the jQuery function will check if the value is present in that array it will fill the second input box with the given text.
Three things:
You need to add an event listener to the first input to constantly keep checking when someone inputs something.
Before selecting elements in the DOM, make sure the DOM is ready.
You don't need jQuery at all here. Like most things, very easy to do without jQuery.
const names = [ "Jcob", "Pete", "Fin", "John" ];
document.addEventListener('DOMContentLoaded', function() {
const fname = document.getElementById('fname');
const lname = document.getElementById('lname');
fname.addEventListener('input', function(event) {
lname.value = names.includes(fname.value) ? 'Bob' : '';
});
});
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
If you insist on jQuery (which I do strongly recommend you shouldn't until you are proficient with the native DOM API):
const names = [ "Jcob", "Pete", "Fin", "John" ];
$(document).ready(function() {
const $fname = $('#fname');
const $lname = $('#lname');
$fname.on('input', function(event) {
if ($.inArray($fname.val(), names) > -1) {
$lname.val('Bob');
} else {
$lname.val('');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
Try this:
<body>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
<button onclick="checkValue()">Click</button>
<script>
var arr1 = ["Jcob", "Pete", "Fin", "John"];
function checkValue() {
var str = $("#fname").val();
var val = jQuery.inArray(str, arr1);
if (val === -1) {
console.log("no value");
}
else {
$("#lname").val("Bob");
}
}
</script>
</body>
I'm trying to receive value as separate object array for each element.
This is my code
<input class="name" name="name[]" type="text" />
<input class="date_of_birth" name="DoB[]" type="text" />
<input class="age" type="radio" name="age" value="1" />
<input class="age" type="radio" name="age" value="0" />
var kidName = [];
$(".name").each(function() {
kidName.push($(this).val());
});
var newDob = [];
$(".date_of_birth").each(function() {
newDob.push($(this).val());
});
var age = [];
$(".age:checked").each(function() {
age.push($(this).val());
});
var kids = {
"kidName": kidName,
"newDob": newDob,
"age": age
};
How i get the value with this as separate array for each element.
kids: {
kidName: ["Test1", "Test2"]
newDob: ["20/02/2000", "20/03/2018"]
age: ["19", "1"]
}
But i want to receive these values like this
kids:
{
kidName: ["Test1"],
newDob: ["20/02/2000"],
age: ["19"]
},
{
kidName: ["Test2"],
newDob: ["20/03/2018"],
age: ["1"]
}
How can i achieve this, what changes should i make to receive values like this?
Thanks
One option is to put the form group into a container. Select the container and use map to loop thru the containers. In this example, the container is a div with class input-group
Note: you need to change the name of radio button every container.
var result = $(".input-group").map(function() {
return {
kidName: $(this).find('.name').val(),
newDob: $(this).find('.date_of_birth').val(),
age: $(this).find('.age:checked').val(),
}
}).get();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group">
<input class="name" name="name[]" type="text" value="Test1" />
<input class="date_of_birth" name="DoB[]" type="text" value="20/02/2000" />
<input class="age" type="radio" name="age01[]" value="1" checked/>
<input class="age" type="radio" name="age01[]" value="0" />
</div>
<div class="input-group">
<input class="name" name="name[]" type="text" value="Test2" />
<input class="date_of_birth" name="DoB[]" type="text" value="20/03/2018" />
<input class="age" type="radio" name="age02[]" value="1" />
<input class="age" type="radio" name="age02[]" value="0" checked/>
</div>
Based on what is present in your question, the best I can suggest is just to reformat the data you have into the format you need.
Id you're able to provide your html, it may be possible to get the data into this format initially rather than reparsing it.
const kids = {
kidName: ["Test1", "Test2"],
newDob: ["20/02/2000", "20/03/2018"],
age: ["19", "1"],
};
const kidsArraysToObjects = kids => kids.kidName.map(
(_, i) => Object.keys(kids).reduce((prev, curr) => ({
...prev,
[curr]: kids[curr][i]
}), {})
)
const result = kidsArraysToObjects(kids)
console.dir(result)
Here is what i have tried
var kids = []
$(".name").each(function(index, value) {
if (kids[index] == undefined) {
kids[index] = {}
}
kids[index].kidName = $(this).val()
});
$(".date_of_birth").each(function(index, value) {
if (kids[index] == undefined) {
kids[index] = obj
}
kids[index].newDob = $(this).val()
});
$(".age:checked").each(function(index, value) {
if (kids[index] == undefined) {
kids[index] = obj
}
kids[index].age = $(this).val()
});
NOTE: I haven't tested this
try this replace parent-selector-each-record with common class or id of each row
by using this approach you get exact data. also you can use #OliverRadini approach
var kids = [];
$("parent-selector-each-record").each(function() {
var kid = {};
kid["kidName"] = $(this).find(".name").val()
kid["newDob"] = $(this).find(".date_of_birth").val()
kid["age"] = $(this).find(".age:checked").val()
kids.push(kid);
});
I also suggest to reformat your object structure after that you get the data, since it will avoid some coupling with your HTML. In other words, it avoids to touch your JavaScript when you want to change your HTML.
const kids = {
kidName: ["Test1", "Test2"],
newDob: ["20/02/2000", "20/03/2018"],
age: ["19", "1"]
}
const keys = Object.keys(kids);
const result = kids[keys[0]].map((_, i) => {
return keys.reduce((obj, key) => {
obj[key] = kids[key][i];
return obj;
}, {});
});
console.log(result);
I have seen this method of serializing a form to JSON and it's working fine. My question is: How can I achieve this with pure JavaScript, without using any jQuery code? I am sorry if the question is dumb, but I'm still learning so if anyone can help me, I'll be grateful.
(function ($) {
$.fn.serializeFormJSON = function () {
var objects = {};
var anArray = this.serializeArray();
$.each(anArray, function () {
if (objects[this.name]) {
if (!objects[this.name].push) {
objects[this.name] = [objects[this.name]];
}
objects[this.name].push(this.value || '');
} else {
objects[this.name] = this.value || '';
}
});
return objects;
};
})(jQuery);
$('form').submit(function (e) {
e.preventDefault();
var data = $(this).serializeFormJSON();
console.log(data);
/* Object
email: "value"
name: "value"
password: "value"
*/
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" />
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<p>
<input type="submit" value="Send" />
</p>
</form>
P.S.
Also in jQuery is this the right way to send multiple JSON objects from user input as One String, because I am searching for a way to do that?
You can try something like this:
function formToJson(){
var formElement = document.getElementsByTagName("form")[0],
inputElements = formElement.getElementsByTagName("input"),
jsonObject = {};
for(var i = 0; i < inputElements.length; i++){
var inputElement = inputElements[i];
jsonObject[inputElement.name] = inputElement.value;
}
return JSON.stringify(jsonObject);
}
This solution works only if you have a single form on the page, to make it more general the function could e.g. take the form element as an argument.
You can use Array.reduce, something like
// get array of all fields and/or selects (except the button)
const getFields = () => Array.from(document.querySelectorAll("input, select"))
.filter(field => field.type.toLowerCase() !== "button");
// get id, name or create random id from field properties
const getKey = field => field.name
|| field.id
|| `unknown-${Math.floor(1000 * Math.random()).toString(16)}`;
// get data, simple object
const getFormData = () => getFields()
.reduce( (f2o, field) => ({...f2o, [getKey(field)]: field.value}), {} );
// log the result
const logResult = txt => document.querySelector("#result").textContent = txt;
// get data, array of field objects
const getMoreFormData = () => getFields()
.reduce( (f2o, field) =>
f2o.concat({
id: field.id || "no id",
name: field.name || "no name",
idGenerated: getKey(field),
type: field.type,
value: field.value }
),
[] );
// handling for buttons
document.addEventListener("click", evt => {
if (evt.target.nodeName.toLowerCase() === "button") {
console.clear();
logResult(/simple/.test(evt.target.textContent)
? JSON.stringify(getFormData(), null, " ")
: JSON.stringify(getMoreFormData(), null, " ")
);
}
} );
<form action="#" method="post">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" value="Pete"/>
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" value="pete#here.com"/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<div>
<label>Field without name or id</label>
<input type="number" value="12345" />
</div>
</form>
<p>
<button>Data simple object</button> <button>Data fields array</button>
</p>
<pre id="result"></pre>
Remember that for checkboxes, value attribute can be either on or off string. This is unwanted. Here is my solution, based on this codepen.
let json = Array.from(form.querySelectorAll('input, select, textarea'))
.filter(element => element.name)
.reduce((json, element) => {
json[element.name] = element.type === 'checkbox' ? element.checked : element.value;
return json;
}, {});
OR
let json = {};
Array.from(form.querySelectorAll('input, select, textarea'))
.filter(element => element.name)
.forEach(element => {
json[element.name] = element.type === 'checkbox' ? element.checked : element.value;
});
OR (with typescript)
export type FormJson = {[key: string]: boolean | string};
export const toJson = (form: HTMLFormElement): FormJson =>
Array.from(form.querySelectorAll<HTMLFormElement>('input, select, textarea'))
.filter(element => element.name)
.reduce<FormJson>((json, element) => {
json[element.name] = element.type === 'checkbox' ? element.checked : element.value;
return json;
}, {});
To serialize your form you can do this (note that I added an onsubmit in the form tag):
HTML and JavaScript:
function serializeForm(e) {
e.preventDefault(); // prevent the page to reload
let form = e.target; // get the form itself
let data = new FormData(form); // serialize input names and values
let objSerializedForm = {}; // creating a new object
for (let [name, value] of data) { // iterating the FormData data
objSerializedForm[name] = value; // appending names and values to obj
}
console.log(objSerializedForm);
}
<form action="#" method="post" onsubmit="serializeForm(event)">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" />
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<p>
<input type="submit" value="Send" />
</p>
</form>
Than you can do whatever you want with your objSerializedForm, getting each value by calling objSerializedForm.name.
I have used the struts json plugin and tried to convert the form data to json format to submit by ajax.
I have two cases in the HTML
<form>
<input type="text" name="user.name" value="Tom"></p>
<input type="text" name="user.location" value="China"></p>
<input type="text" name="user.data[0].id" value="993"></p>
<input type="text" name="user.data[0].accountId" value="123"></p>
<input type="text" name="user.data[1].id" value="222"></p>
<input type="text" name="user.data[1].accountId" value="333"></p>
</form>
What I expected is to convert it to the json structure:
{
user : {
name: "Tom",
location : "China",
data: [
{
id : 993,
accountId : 123
},
{
id : 222,
accountId : 333
}
]
}
}
I know how to declare the json data and declare the attributes one by one.
I would like to have the better way to make each form to be in json format using simple way rather than declaring the parameter one by one in json format.
Appreciate for any suggestion or advice. Thank you.
Provided your form is exactly like that
Using a plain JS approach
<form class="userform">
<input type="text" class="username" value="Tom"></p>
<input type="text" class="userlocation" value="China"></p>
<input type="text" class="userid" value="993"></p>
<input type="text" class="useraccountid" value="123"></p>
<input type="text" class="userid2" value="222"></p>
<input type="text" class="useraccountid2" value="333"></p>
</form>
Then assign the values to the object
var frm = document.getElementsByClassName('userform');
//initialize blank object and keys
var user = {},
user.name = "",
user.location = "",
user.data = [];
//get all child input elements
for(var i = 0; i < frm.length; i++){
var uname = frm[i].getElementsByClassName('username')[0];
var uloc = frm[i].getElementsByClassName('userlocation')[0];
var uid = frm[i].getElementsByClassName('userid')[0];
var uaccid = frm[i].getElementsByClassName('useraccountid')[0];
var uid = frm[i].getElementsByClassName('userid2')[0];
var uaccid = frm[i].getElementsByClassName('useraccountid2')[0];
//assign values to object here
user[name] = {}; //assigning a parent property here, the name for example.
user[name].name = uname.value;
user[name].location = uloc.value;
user[name].data.push({
'id': uid.value
'accountId': uaccid.value
});
user[name].data.push({
'id': uid2.value
'accountId': uaccid2.value
});
}
JSON.stringify(user); //convert to JSON (or ignore if you want a plain object)
Output would be this in JSON format
{
user :{
Tom: {
name: "Tom",
data: [
{
id : 993,
accountId : 123
},
{
id : 222,
accountId : 333
}
]
},
Jerry: {
//more data
},
Courage: {
//more data
}
}
}
Hope this helps
If your input fields are many, like id3, accountid3, 4, 5, 6. You have to loop through the classes that you assign to these two repetitive fields
Here you go with a solution using jQuery https://jsfiddle.net/pnz8zrLx/2/
var json = {};
$('button').click(function(){
$('form').each(function(i){
json["user" + i] = {};
json["user" + i].data = [];
var tempJSON = {};
$('form:nth-child(' + (i+1) + ') input[type="text"]').each(function(){
if($(this).attr('name') === 'name' || $(this).attr('name') === 'location'){
json["user" + i][$(this).attr('name')] = $(this).val();
} else {
tempJSON[$(this).attr('name')] = $(this).val();
if(tempJSON != {} && $(this).attr('name') === 'accountId'){
json["user" + i].data.push(tempJSON);
tempJSON = {};
}
}
});
});
console.log(json);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="name" value="Tom">
<input type="text" name="location" value="China">
<input type="text" name="id" value="993">
<input type="text" name="accountId" value="123">
<input type="text" name="id" value="222">
<input type="text" name="accountId" value="333">
</form>
<form>
<input type="text" name="name" value="Test">
<input type="text" name="location" value="Test112">
<input type="text" name="id" value="22">
<input type="text" name="accountId" value="78">
<input type="text" name="id" value="00">
<input type="text" name="accountId" value="44">
</form>
<button>
Submit
</button>
Hope this will help you.
I have the following form ...
<form id="my-form">
<fieldset name="address">
<input name="streetAddress" type="text" placeholder="Street Address"><br>
<input name="city" type="text" placeholder="City"><p>,</p>
<input name="state" type="text" placeholder="State">
<input name="zipCode" type="text" placeholder="Zip Code">
</fieldset>
<fieldset name="dimensions">
<input name="length" type="text" placeholder="length">
<input name="width" type="text" placeholder="width">
<input name="height" type="text" placeholder="height">
</fieldset>
</form>
I need to serialize it into JSON with JS, but I need to have the address's fields warped in an address object, and the dimensions's fields warped in a dimensions object.
Something like this ...
{
'address':{'streetAddress':'111 Candy Ln', 'city':'Los Angeles', ...},
'dimensions':{...}
}
How do you do this cleanly, idealy without having to write my own function for doing this? I have of course seen scripts to serialize, but nothing that will do embedded objects.
Have you tried putting all the fields into arrays?
<fieldset name="address">
<input name="address[streetAddress]" type="text" placeholder="Street Address"><br>
<input name="address[city]" type="text" placeholder="City"><p>,</p>
<input name="address[state]" type="text" placeholder="State">
<input name="address[zipCode]" type="text" placeholder="Zip Code">
</fieldset>
Heres an example, using the serializeObject plugin
Just include that script and you can convert any form into a multi layered JSON object.
DEMO HERE
Using this plugin...more info here Convert form data to JavaScript object with jQuery
(function($){
$.fn.serializeObject = function(){
var self = this,
json = {},
push_counters = {},
patterns = {
"validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
"key": /[a-zA-Z0-9_]+|(?=\[\])/g,
"push": /^$/,
"fixed": /^\d+$/,
"named": /^[a-zA-Z0-9_]+$/
};
this.build = function(base, key, value){
base[key] = value;
return base;
};
this.push_counter = function(key){
if(push_counters[key] === undefined){
push_counters[key] = 0;
}
return push_counters[key]++;
};
$.each($(this).serializeArray(), function(){
// skip invalid keys
if(!patterns.validate.test(this.name)){
return;
}
var k,
keys = this.name.match(patterns.key),
merge = this.value,
reverse_key = this.name;
while((k = keys.pop()) !== undefined){
// adjust reverse_key
reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');
// push
if(k.match(patterns.push)){
merge = self.build([], self.push_counter(reverse_key), merge);
}
// fixed
else if(k.match(patterns.fixed)){
merge = self.build([], k, merge);
}
// named
else if(k.match(patterns.named)){
merge = self.build({}, k, merge);
}
}
json = $.extend(true, json, merge);
});
return json;
};
})(jQuery);
I have two solutions for this:
Name the fields after the fieldsets (like the proposal above): address[street], address[zipcode], etc.
Give the fieldsets some unique id's.
In both cases I suggest you using this library I made: https://github.com/serbanghita/formToObject
Call it like this:
Case 1: var myFormObj = new formToObject('myFormId');
Case 2: var myFormObj = new formToObject('myFieldsetId');