How to fill form with JSON? - javascript

I get ajax response as JSON and need to fill a form with it. How to do that in jQuery or something else ? Is something better than using $(json).each() ?
JSON:
{
"id" : 12,
"name": "Jack",
"description": "Description"
}
Form to fill
<form>
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="text" name="description"/>
</form>

var json={
"id" : 12,
"name": "Jack",
"description": "Description"
};
for(key in json)
{
if(json.hasOwnProperty(key))
$('input[name='+key+']').val(json[key]);
}
srry i thought it was the id property that was set.
here: http://jsfiddle.net/anilkamath87/XspdN/

Came here searching for a solution that didn't involve jQuery or a brunch of DOM scaning, but didn't find one... so here is my vanilla js solution brought to you other guys that probably ditched jQuery long ago.
const data = {
"id" : 12,
"name": "Jack",
"description": "Description",
"nonExisting": "works too"
}
const { elements } = document.querySelector('form')
for (const [ key, value ] of Object.entries(data) ) {
const field = elements.namedItem(key)
field && (field.value = value)
}
<form>
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="text" name="description"/>
</form>

Assuming data is the JSON object, you could use this inside the $.getJSON callback:
var $inputs = $('form input');
$.each(data, function(key, value) {
$inputs.filter(function() {
return key == this.name;
}).val(value);
});

Pretty simple in pure JavaScript:
https://jsfiddle.net/ryanpcmcquen/u8v47hy9/
var data = {
foo: 1,
bar: 2
};
var inputs = Array.prototype.slice.call(document.querySelectorAll('form input'));
Object.keys(data).map(function (dataItem) {
inputs.map(function (inputItem) {
return (inputItem.name === dataItem) ? (inputItem.value = data[dataItem]) : false;
});
});
<form>
<input name="foo">
<input name="bar">
</form>
Edit: This also works with other inputs such as select, simply by replacing document.querySelectorAll('form input') with document.querySelectorAll('form input, form select').
This also gets around the global leak in this answer:
https://stackoverflow.com/a/6937576/2662028

jQuery Populate plugin and code proposed by #Mathias inspired me to make my own plugin:
Here my myPopulate plugin code. It use attr parameter as name of elements attribute on to use for identifying them.
(function($) {
$.fn.myPopulate = function(json, attr) {
var form = $(this);
$.each(json, function(key, value) {
form.children('[' + attr + '="' + key + '"]').val(value);
});
};
})(jQuery);
Using:
{
"id" : 12,
"name": "Jack",
"description": "Description"
}
form1 (matching by name attribute):
<form>
<input type="text" name="name" />
<input type="text" name="id" />
<textarea type="text" name="description" />
</form>
$('#form1').myPopulate(json, 'name');
form2 (matching by alt attribute):
<form id="form2">
<input type="text" name="nick" alt="name" />
<input type="text" name="identifier" alt="id" />
<textarea type="text" name="desc" alt="description" />
</form>
$('#form2').myPopulate(json, 'alt');

I'm using this method with iCheck elements. This method can work native check and radio inputs.
populateForm(frm, data) {
console.log(data);
$.each(data, function(key, value) {
var ctrl = $("[name=" + key + "]", frm);
switch (ctrl.prop("type")) {
case "radio":
if (
ctrl.parent().hasClass("icheck-primary") ||
ctrl.parent().hasClass("icheck-danger") ||
ctrl.parent().hasClass("icheck-success")
) {
// raido kutularında aynı isimden birden fazla denetçi olduğu için bunları döngüyle almak lazım
// multiple radio boxes has same name and has different id. for this we must look to each html element
$.each(ctrl, function(ctrlKey, radioElem) {
radioElem = $(radioElem);
console.log(radioElem);
console.log(radioElem.attr("value"));
if (radioElem.attr("value") == value) {
radioElem.iCheck("check");
} else {
radioElem.iCheck("uncheck");
}
});
} else {
$.each(ctrl, function(ctrlKey, radioElem) {
radioElem = $(radioElem);
console.log(radioElem);
console.log(radioElem.attr("value"));
if (radioElem.attr("value") == value) {
radioElem.attr("checked", value);
} else {
radioElem.attr("checked", value);
}
});
}
break;
case "checkbox":
if (
ctrl.parent().hasClass("icheck-primary") ||
ctrl.parent().hasClass("icheck-danger") ||
ctrl.parent().hasClass("icheck-success")
) {
if (ctrl.attr("value") == value) {
ctrl.iCheck("check");
} else {
ctrl.iCheck("uncheck");
}
} else {
ctrl.removeAttr("checked");
ctrl.each(function() {
if (value === null) value = "";
if ($(this).attr("value") == value) {
$(this).attr("checked", value);
}
});
}
break;
default:
ctrl.val(value);
}
});
}
Example form:
<form id="form1">
<div className="form-group row">
<label className="col-sm-3 col-form-label">
{window.app.translate(
"iCheck Radio Example 1"
)}
</label>
<div className="col-sm-9">
<div className="icheck-primary">
<input
type="radio"
id="radio1_0"
name="radio1"
value="0"
/>
<label for="radio1_0">
{window.app.translate(
"Radio 1 0"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio1_1"
name="radio1"
value="1"
/>
<label for="radio1_1">
{window.app.translate(
"Radio 1 1"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio1_2"
name="radio1"
value="2"
/>
<label for="radio1_2">
{window.app.translate(
"Radio 1 2"
)}
</label>
</div>
</div>
</div>
<div className="form-group row">
<label className="col-sm-3 col-form-label">
{window.app.translate(
"iCheck Radio Example 2"
)}
</label>
<div className="col-sm-9">
<div className="icheck-primary">
<input
type="radio"
id="radio2_0"
name="radio2"
value="0"
/>
<label for="radio2_0">
{window.app.translate(
"Radio 2 0"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio2_1"
name="radio2"
value="1"
/>
<label for="radio2_1">
{window.app.translate(
"Radio 2 1"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio2_2"
name="radio2"
value="2"
/>
<label for="radio2_2">
{window.app.translate(
"Radio 2 2"
)}
</label>
</div>
</div>
</div>
<div className="form-group row">
<label
htmlFor="ssl"
className="col-sm-3 col-form-label"
>
{window.app.translate("SSL")}
</label>
<div className="col-sm-9">
<div className="form-group row">
<div className="col-sm-12">
<div className="icheck-primary d-inline">
<input
type="checkbox"
id="ssl"
name="ssl"
value="1"
/>
<label for="ssl" />
</div>
</div>
</div>
</div>
</div>
</form>
Example json data:
{
"radio1": "3",
"radio2": "1",
"ssl": "0"
}
Edit: I tried populate plugin but it doesn't working with iCheck and other things for example select2, chosen, etc...

You might want to take a look at the jQuery Populate plugin.
Although if this is the only use case you have, you might as well do it manually.

Just use a JSON plugin for jQuery - such as jquery-json.

You might also consider usage of jQuery templates for that purpose:
http://api.jquery.com/jQuery.template/

First you need to parse the JSON string so that you get an object that you can use:
var o = $.parseJSON(json);
(Note: You can also specify the data type 'json' in the AJAX call, then it will be parsed into an object already when you get the result.)
Then you can loop throught the properties in the object:
$.each(o, function(key, value){
$('form [name=' + key + ']').val(value);
});

I haven't seen a solution that accounts for a form with nested properties.
Here it is.
//pass in the parent object name, if there is one
let parentName = 'optional';
SyncJsonToForm(data, parentName);
function SyncJsonToForm(obj, path = '') {
let subpath = path === '' ? path : path + '.';
$.each(obj, function (key, value) {
let jsonPath = subpath + key;
// to debug a particular field (or multiple fields), replace the following JsonPath(s) with the desired property(ies)
if ([''].includes(jsonPath)) {
console.log(jsonPath);
debugger;
}
// update the value for the jsonPath
$(`[name="${jsonPath}"]`).val(value);
if (typeof value === "object") {
SyncJsonToForm(value, jsonPath);
}
});
}

Related

How to use global variable so i can use it on my javascript module

i want to get all of this input values to my budget app
but i have problem to get values of the radio button because it says its undefined. i create global function to get by radio button value. but the others is in javascript module.
https://jsfiddle.net/8k3gw7ty/
<div class="button_income">
<input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
<label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
<input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
<label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
<label class="labelinput" for="input-desc">Your Income/Expense Description</label>
<input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
<label class="labelinput" for="input-val">Value of Income/Expense</label>
<input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
Actually there was no default value for your val variable. Since val will only get value when you click on the checkbox (according to your code).
Also you were returning val which isn't necessary. I've also removed the budgetController.
Hope this'll help.
let val = 'inc'; // default value
function getButtonValue() {
var type = document.getElementsByName("type");
if (type[0].checked) {
val = type[0].value
} else if (type[1].checked) {
val = type[1].value
}
}
const domController = (function() {
return {
getInput: function() {
return {
type: val,
description: document.querySelector(".input_description").value || 0,
value: parseFloat(document.querySelector(".input_value").value) || 0
}
}
}
})();
const controller = (function( UI) {
var ctrlAddItem = function() {
var input = UI.getInput();
console.log(input);
}
document.querySelector(".addbtn").addEventListener("click", ctrlAddItem)
document.addEventListener("keypress", function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrlAddItem();
}
});
})( domController);
<div class="button_income">
<input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
<label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
<input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
<label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
<label class="labelinput" for="input-desc">Your Income/Expense Description</label>
<input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
<label class="labelinput" for="input-val">Value of Income/Expense</label>
<input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
<button><i class="fas fa-check addbtn">Save</i></button>

Save and load checkboxes state to file

I want to save state of selected checkbox to a file (whether as a text file or something else) that contains information on what was checked.
I can't use localstorage or cookies, I need it saved as external file so I can save (and load) several files with different checkmarks selected.
It's pretty straightforward, but I can't find any solution that does exactly this, so any help is appreciated.
Simple snippet for reference:
div {
display: table;
}
span {
display: block;
}
input,
label {
display: inline-block;
}
<div>
<span>
<input id="box1" type="checkbox" />
<label for="box1">Checkbox 1</label>
</span>
<span>
<input id="box2" type="checkbox" checked/>
<label for="box2">Checkbox 2</label>
</span>
<span>
<input id="box3" type="checkbox" />
<label for="box3">Checkbox 3</label>
</span>
</div>
<button id="_save">Save</button>
<button id="_load">Load</button>
Ok, I have a solution that does what I needed.
So when you check everything you want from your form, you can save it into localstorage and THEN you can export localstorage as JSON. I found this google extension that handles import and export for the localstorage (in a textual file), but you can always go extra mile and write your own script for that.
Here is JSFiddle for the localstorage so can save whatever input you want and here is chrome extension that handles import and export LocalStorage Manager.
Javascript:
;(function($) {
$.fn.toJSON = function() {
var $elements = {};
var $form = $(this);
$form.find('input, select, textarea').each(function(){
var name = $(this).attr('name')
var type = $(this).attr('type')
if(name){
var $value;
if(type == 'radio'){
$value = $('input[name='+name+']:checked', $form).val()
} else if(type == 'checkbox'){
$value = $(this).is(':checked')
} else {
$value = $(this).val()
}
$elements[$(this).attr('name')] = $value
}
});
return JSON.stringify( $elements )
};
$.fn.fromJSON = function(json_string) {
var $form = $(this)
var data = JSON.parse(json_string)
$.each(data, function(key, value) {
var $elem = $('[name="'+key+'"]', $form)
var type = $elem.first().attr('type')
if(type == 'radio'){
$('[name="'+key+'"][value="'+value+'"]').prop('checked', true)
} else if(type == 'checkbox' && (value == true || value == 'true')){
$('[name="'+key+'"]').prop('checked', true)
} else {
$elem.val(value)
}
})
};
}( jQuery ));
//
// DEMO CODE
//
$(document).ready(function(){
$("#_save").on('click', function(){
console.log("Saving form data...")
var data = $("form#myForm").toJSON()
console.log(data);
localStorage['form_data'] = data;
return false;
})
$("#_load").on('click', function(){
if(localStorage['form_data']){
console.log("Loading form data...")
console.log(JSON.parse(localStorage['form_data']))
$("form#myForm").fromJSON(localStorage['form_data'])
} else {
console.log("Error: Save some data first")
}
return false;
})
});
HTML:
<form action="#" method="get" id="myForm">
<input type="text" name="textfield">
Textfield
<br/>
<input type="number" name="numberfield" />
Numberfield
<br/>
<input type="radio" name="radiofield" value="1" />
<input type="radio" name="radiofield" value="2" />
<input type="radio" name="radiofield" value="3" />
Radiofields
<br/>
<input type="checkbox" name="checkfield">
<input type="checkbox" name="checkfield2">
<input type="checkbox" name="checkfield3">
Checkboxes
<br/>
<select name="selectbox">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Selectbox
<br/>
<textarea name="textarea"></textarea>
Textarea
<br/>
<hr/>
<button id="_save">Save</button>
<button id="_load">Load</button>
<input type="reset">
</form>

How to show form fields on keyup

I've been working on this for weeks now and I can't seem to get the hang of this. I'm trying to show the hidden fields only when the previous fields are entered. Here's my example code:
HTML
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1" />
<br/>
<label>Field 2:</label>
<input type="text" class="field2" />
<br/>
<label>Field 3:</label>
<input type="text" class="field3" />
<br/>
</div>
<div id="group2">
<label>Field 4:</label>
<input type="text" class="field4" />
<br/>
<label>Field 5:</label>
<input type="text" class="field5" />
<br/>
<label>Field 6:</label>
<input type="text" class="field6" />
<br/>
</div>
<div id="group3">
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 9:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>
</form>
CSS
#group2 {
visibility: hidden;
}
#group3 {
visibility: hidden;
}
Script
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
CheckSubmit();
});
function CheckSubmit() {
var x = true;
$('#group1').find('input[type="text"]').keyup(function () {
if ($(this).val().length === 0) {
x = false;
return;
}
});
if (x) {
$('#group2').css('visibility', 'visible');
$('#group3').css('visibility', 'visible');
} else {
$('#group2').css('visibility', 'hidden');
$('#group3').css('visibility', 'hidden');
}
CheckSubmit();
});
I'm not sure what I'm doing wrong here. Can someone please assist?
I changed your code a bit. I stored the relevant selectors in variables, so you don't need to do a lot of re-querying every time something changes.
Here's the updated code:
JavaScript
var inputs = $('#group1').find('input[type="text"]');
var hidden = $('#group2, #group3');
inputs.keyup(function() {
var test = true;
inputs.each(function(key, value) {
if (!$(this).val().length) {
test = false;
return false;
}
});
hidden.css('visibility', ( test ? 'visible' : 'hidden' ) );
});
Demo
Try before buy
You can make this more dynamic by checking the inputs in the current div and if they all have a value, then show the next div (if there is one).
If they clear a value, then hide all the later divs.
$(document).ready(function() {
// you can restrict this to inputs in a specific div or just any input
$('#group1 input').on('keyup', function () {
var parentDiv = $(this).closest('div')
var hasValues = parentDiv.find('input').filter(function() {
return this.value == '';
}).length == 0;
if(hasValues) {
//parentDiv.next().css('visibility', 'visible'); // show just the next section
parentDiv.nextAll().css('visibility', 'visible'); // show all later sections
} else {
parentDiv.nextAll().css('visibility', 'hidden');
}
});
});
DEMO
I made a quick pen with a solution. It may not be the prettiest but it get's it done. Basically on every keyup event I check #group1's children for their value length and if they all have a length that's more than 0 I change a flag in an array. If all 3 flags are true I show #group2.
Here's the pen
$('#group2').hide();
$('#group3').hide();
$('#group1').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group1 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group2').show();
}
});
$('#group2').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group2 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group3').show();
}
});
Hope it helps :D
If I understand your question well, you want to show the fields in #group2/-3 if all the fields in the previous fields have a value. Using a few data-*-attributes (see MDN), you can create a handler like this (if you prefer: jsFiddle, containing a more complete example):
$('[data-nextgroup] [type=text]').on('keyup', function (e){
var fieldgroup = $(this.getAttribute('data-group'))
,fields = fieldgroup.find('[type=text]')
,canshow = fields.length ===
fields.filter( function (i,el) { return el.value.length; } ).length;
void( canshow && $(fieldgroup.attr('data-nextgroup')).fadeIn() );
});
[data-hidden] {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="group1" data-nextgroup="#group2">
<label>Field 1:</label>
<input type="text" class="field1" data-group="#group1"/>
<br/>
<label>Field 2:</label>
<input type="text" class="field2" data-group="#group1"/>
<br/>
<label>Field 3:</label>
<input type="text" class="field3" data-group="#group1"/>
<br/>
</div>
<div id="group2" data-nextgroup="#group3" data-hidden>
<label>Field 4:</label>
<input type="text" class="field4" data-group="#group2"/>
<br/>
<label>Field 5:</label>
<input type="text" class="field5" data-group="#group2"/>
<br/>
<label>Field 6:</label>
<input type="text" class="field6" data-group="#group2"/>
<br/>
</div>
<div id="group3" data-groups data-hidden>
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 8:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>

Convert forms with inputs that have same name to JSON

I have a form like so that collects information about a users car:
<form id="car" action="" method="">
<section class="inputContainer">
<section class="carInfo">
<input type="text" name="Make" class="make" />
<input type="text" name="Model" class="model" />
<input type="text" name="Year" class="year" />
<input type="text" name="Color" class="color" />
</section>
</section>
<input type="hidden" name="AllCarData" />
<a class="addAnotherCar" href="#">Add another car</a>
<input type="submit" value="Submit" />
</form>
When the user clicks the 'Add another car' link, my JS duplicates the 'carInfo' group of inputs and appends it to 'inputContainer'; creating a new set of form inputs like so:
<form id="car" action="" method="">
<section class="inputContainer">
<section class="carInfo">
<input type="text" name="Make" class="make" />
<input type="text" name="Model" class="model" />
<input type="text" name="Year" class="year" />
<input type="text" name="Color" class="color" />
</section>
<section class="carInfo">
<input type="text" name="Make" class="make" />
<input type="text" name="Model" class="model" />
<input type="text" name="Year" class="year" />
<input type="text" name="Color" class="color" />
</section>
</section>
<input type="hidden" name="AllCarData" />
<a class="addAnotherCar" href="#">Add another car</a>
</form>
Once the user clicks submit, I want to parse the form into a JSON object and inject it into a hidden input field. JSON for two cars should look like this:
[{ "Make" : "Mazda" , "Model": "Protege" , "Year" : "2002" , "Color" : "Red" } , { "Make" : "Toyota" , "Model": "Camery" , "Year" : "2012" , "Color" : "Blue" }]
I am currently getting the input's name to serve as the key and the entered value as the value. I have the following function built:
CreateJson: function () {
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var carDataString = JSON.stringify($('.inputContainer input').serializeObject());
console.log(carDataString);
$("input[name='AllCarData']").val(carDataString);
}
};
********The only problem is that since the additional inputs that are duplicated when a user chooses to add another car use the same 'name', my JSON is only outputting one set of values insead of multiple (when multiple cars are added). http://jsfiddle.net/njacoy/jLopamk7/
Note: I am using the jQuery validate plugin to validate this form. It's set to look for input names.
Thanks!
Try this -
$.fn.serializeObject = function (data) {
var els = $(this).find(':input').get();
if (typeof data != 'object') {
// return all data
data = {};
$.each(els, function () {
if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
data[this.name] = $(this).val();
}
});
return data;
}
};
$("#car").submit(function () {
var data = [];
$(this).find(".inputContainer section").each(function () {
data[data.length] = $(this).serializeObject();
})
var carDataString=JSON.stringify(data);
console.log(carDataString);
$("input[name='AllCarData']").val(carDataString);
return false
});
here's the working fiddle http://jsfiddle.net/vikrant47/jLopamk7/4/
You would serialise the inputs in each section separately, then get them as an array and use stringify on that:
var carDataString = JSON.stringify(
$('.inputContainer section').map(function(i, o){
return o.find('input').serializeObject();
}).get()
);

How to serialize checkbox value through searilizedarray()?

My question is how to serialize checkbox value and textbox value together in one array through searilizedarray()...
now i am getting something like this
[{"name":"text_input","value":"kalpit"},
{"name":"wpc_chkbox[]","value":"Option one"},
{"name":"wpc_chkbox[]","value":"Option two"},
{"name":"wpc_chkboxasdf[]","value":"Option one"},
{"name":"wpc_chkboxasdf[]","value":"Option two"},
{"name":"wpc_inline_chkbox[]","value":"1"},
{"name":"wpc_inline_chkbox[]","value":"2"},
{"name":"wpc_inline_chkbox[]","value":"3"},
{"name":"wpc_radios","value":"Option one"}]
but it should be like
[{"name":"text_input","value":"kalpit"},
{"name":"wpc_chkbox[]","value":"[Option one,Option Two]"},
{"name":"wpc_chkboxasdf[]","value":"[Option one,Option Two]"},
{"name":"wpc_inline_chkbox[]","value":"[1,2,3]"},
{"name":"wpc_radios","value":"Option one"}]
i am using var form = $('.wpc_contact').serializeArray(); to get form data
this is my html sample which I am generating dynamically using drag and drop future..
<form method="POST" name="1" class="form-horizontal wpc_contact" novalidate="novalidate">
<fieldset>
<div id="legend" class="">
<legend class="">Demo</legend>
<div id="alert-message" class="alert hidden" style="color: red;"></div>
</div>
<div class="control-group">
<label class="control-label">Checkboxes</label>
<div class="controls" name="wpc_chkbox" req="yes">
<input type="checkbox" value="Option one" id="wpc_chkbox_0" name="wpc_chkbox[]" req="yes"> Option one
<input type="checkbox" value="Option two" id="wpc_chkbox_1" name="wpc_chkbox[]" req="yes"> Option two
</div>
</div>
<div class="control-group">
<div class="controls" name="wpc_inline_chkbox" req="yes">
<input type="checkbox" value="1" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_0" req="yes"> 1
<input type="checkbox" value="2" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_1" req="yes"> 2
<input type="checkbox" value="3" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_2" req="yes"> 3
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>
Thanks in advance
Try this:
var cacheObject = {};//tmp cache for form elements name/values pairs
var serArr = $('.wpc_contact').serializeArray();
//set values of elements to cacheObject
$.each(serArr, function (arrayIndex,obj) {
if (cacheObject[obj.name]) {
cacheObject[obj.name].push(obj.value);
} else {
cacheObject[obj.name] = [obj.value];
}
});
//create new serialized array
var newSerArr = [];
$.each(cacheObject, function (key, value) {
var obj = {};
obj[key] = value;
newSerArr.push(obj);
});
console.log(newSerArr);//looks like serializeArray
This one makes a different array and elements of same name are grouped together.
var form_data = $(".wpc_contact").serializeArray();
var form_array = {}; //final array where all the values will be stored
$.each(form_data, function(i, element) {
if(jQuery('input[name="'+element.name+'"]:checked').length>0)
{
replaced = element.name.replace('[]',''); //removing [] from the input name
form_array[replaced]={};
jQuery('input[name="'+element.name+'"]:checked').each(function(j,ind){
form_array[replaced][j] = jQuery(this).val();
});
}
else
{
form_array[element.name] = element.value;
}
});
console.log(form_array);
You can access as:
alert(form_array['wpc_chkbox'][0]); //no '[]' in the key

Categories