Convert form fields into JSON object - javascript

I have the following form:
<form id="myForm" method="POST">
<input type="text" name="matrix[]" value="1"/><br/>
<input type="text" name="matrix[]" value="2"/><br/>
<input type="text" name="matrix[]" value="3"/><br/>
<input type="text" name="multi_matrix[colors][]" value="red"/><br/>
<input type="text" name="multi_matrix[colors][]" value="blue"/><br/>
<input type="text" name="multi_matrix[weight][]" value="75"/><br/>
<input type="text" name="multi_matrix[weight][]" value="83"/><br/>
<input type="submit" value="Send">
</form>
now I want to use JavaScript/jQuery to convert those values into JSON string. When I use JSON.stringify($("#myForm").serializeArray()) code then it returns the following:
[{"name":"matrix[]","value":"1"},{"name":"matrix[]","value":"2"},{"name":"matrix[]","value":"3"},{"name":"multi_matrix[colors][]","value":"red"},{"name":"multi_matrix[colors][]","value":"blue"},{"name":"multi_matrix[weight][]","value":"75"},{"name":"multi_matrix[weight][]","value":"83"}]
as you can see all fields have a separate entry, but I want to join them together to get the following:
{"matrix":[1,2,3],"multi_matrix":{"colors":["red","blue"],"weight":[75,83]}}
Is there any built-in function that can do this ? Or do I have to iterate through all fields and create JSON manually on my own ?

You can extend jQuery and create a UDF serializeObject like done in this answer, based on the serializeArray():
$.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;
};

My variant:
arr = $("#myForm").serializeArray();
var res={};
var m,o;
arr.forEach(function(item){
m = item.name.match(/[^\]\[]+/g);
o = res;
m.forEach(function(v,i,a){
if(o[v] === undefined) {
if(i+1 !== a.length) {
o[v] = {};
o = o[v];
return;
}
o[v] = [item.value];
} else {
if(i+1 !== a.length) {
o = o[v];
return;
}
o[v].push(item.value);
}
});
})
console.log(res)
$('<pre>'+JSON.stringify(res)+'</pre>').appendTo('#result')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="myForm" method="POST">
<input type="text" name="matrix[]" value="1"/><br/>
<input type="text" name="matrix[]" value="2"/><br/>
<input type="text" name="matrix[]" value="3"/><br/>
<input type="text" name="multi_matrix[colors][]" value="red"/><br/>
<input type="text" name="multi_matrix[colors][]" value="blue"/><br/>
<input type="text" name="multi_matrix[weight][]" value="75"/><br/>
<input type="text" name="multi_matrix[weight][]" value="83"/><br/>
<input type="text" name="multi_matrix[weight_real][]" value="83.32"/><br/>
<input type="text" name="multi_matrix[weight_real][]" value="83.65"/><br/>
<input type="text" name="multi_matrix[price][unreal][]" value="383.32"/><br/>
<input type="text" name="multi_matrix[price][unreal][]" value="183.65"/><br/>
<input type="submit" value="Send">
</form>
<div id="result"></div>
{
"matrix": ["1", "2", "3"],
"multi_matrix": {
"colors": ["red", "blue"],
"weight": ["75", "83"],
"weight_real": ["83.32", "83.65"],
"price": {
"unreal": ["383.32", "183.65"]
}
}
}

Related

Why the output from javascript just shown for a short period of time?

I am developing a Registration form for my assignment. All things are working but when I click on the submit button, the warning messages on the label are just shown for a very short period of time. I am using eclipse and apache tomacat. here is my code.
JSP Code:
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid"/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname"/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname"/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email"/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" onclick="validate()"/>
</form>
Javascript Code:
function validate()
{
var itemid=document.getElementById("itemid").value;
var itemname=document.getElementById("itemname").value;
var uname=document.getElementById("uname").value;
var email=document.getElementById("email").value;
var amount=document.getElementById("amount").value;
var autoincrement=document.getElementById("autoincrement");
var flag=true;
if(itemid.length==0){
flag=false;
document.getElementById("itemid_l").innerHTML="<b>Required field!</b> Item Id: ";
}
if(itemname.length==0){
flag=false;
document.getElementById("itemname_l").innerHTML="<b>Required field!</b> Item Name: ";
}
if(uname.length==0){
flag=false;
document.getElementById("uname_l").innerHTML="<b>Required field!</b> Your Name: ";
}
if(email.length==0){
flag=false;
document.getElementById("email_l").innerHTML="<b>Required field!</b> Your Email Address: ";
}
if(amount.length==0){
flag=false;
document.getElementById("amount_l").innerHTML="<b>Required field!</b> Amount Bid: ";
}
if(!autoincrement.checked){
flag=false;
document.getElementById("autoincrement_l").innerHTML="<b>Required field!</b> Auto-increment to match other bidders:: ";
}
if(flag==true){
alert('Good job!!');
return true;
}
else
{
document.getElementById("msg").innerHTML="Required data is missing. Please fill";
return false;
}
}
Any suggestion will help me a lot..
You can use onsubmit event so that whenever user click on submit button this gets call and if the function validate() return true form will get submitted else it will not submit form .
Demo code :
function validate() {
var itemid = document.getElementById("itemid").value;
var itemname = document.getElementById("itemname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var amount = document.getElementById("amount").value;
var autoincrement = document.getElementById("autoincrement");
var flag = true;
if (itemid.length == 0) {
flag = false;
document.getElementById("itemid_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemid_l").innerHTML = ""
}
if (itemname.length == 0) {
flag = false;
document.getElementById("itemname_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemname_l").innerHTML = "";
}
if (uname.length == 0) {
flag = false;
document.getElementById("uname_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("uname_l").innerHTML = "";
}
if (email.length == 0) {
flag = false;
document.getElementById("email_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("email_l").innerHTML = "";
}
if (amount.length == 0) {
flag = false;
document.getElementById("amount_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("amount_l").innerHTML = "";
}
if (!autoincrement.checked) {
flag = false;
document.getElementById("autoincrement_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("autoincrement_l").innerHTML = "";
}
if (flag == true) {
document.getElementById("msg").innerHTML = "";
alert('Good job!!');
flag = true; //do true
} else {
document.getElementById("msg").innerHTML = "Required data is missing. Please fill";
flag = false; //do false
}
return flag; //return flag
}
<!--add onsubmit -->
<form method="post" id="forms" onsubmit="return validate()">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--give id to span instead of label-->
<label> <span id="itemid_l"></span>Item Id:</label> <input type="text" name="itemid" id="itemid" /><br/>
<label><span id="itemname_l"></span>Item Name:</label> <input type="text" name="itemname" id="itemname" /><br/>
<label><span id="uname_l"></span>Your Name:</label> <input type="text" name="uname" id="uname" /><br/>
<label><span id="email_l"></span>Your Email Address:</label> <input type="text" name="email" id="email" /><br/>
<label><span id="amount_l"></span>Amount Bid:</label> <input type="number" name="amount" id="amount" /><br/>
<label><span id="autoincrement_l"></span>Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" />
</form>
Also , if you just need to check for empty field you can just use required attribute on input tag like below :
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--added required attribute-->
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid" required/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname" required/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname" required/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email" required/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"required/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement" required><br/>
<input type="submit" value="Submit Bid"/>
</form>

Decimal to Fraction Calculator Javascript Issue

I am trying to make Decimal to Fraction Calculator like (https://www.decimal-to-fraction.com/). But I am facing some issues.
I think it's a jquery issue.
Console error shows ($ is not a function)
I have tried this:
$(document).ready(function() {
var params = GetURLParams();
if (Object.keys(params).length > 0 && params.x != "") {
document.getElementById("x").value = params.x;
}
});
function GetURLParams() {
var url = window.location.href;
var regex = /[?&]([^=#]+)=([^&#]*)/g,
params = {},
match;
while (match = regex.exec(url)) {
params[match[1]] = match[2];
}
return params;
}
var gcd2 = function(a, b, f) {
if (f) {
if (b <= 1)
return a;
} else {
if (!b)
return a;
}
return gcd2(b, a % b, f);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="x" name="x" class="intext form-control" tabindex="1">
<button type="button" title="Convert" class="btn btn-lg btn-primary" tabindex="2" onclick="convert()"> Convert</button>
<input class="form-control" type="text" id="y" tabindex="5" readonly>
<input class="form-control" type="text" id="n" tabindex="6" readonly>
<canvas id="frac"></canvas>
<input class="form-control" type="text" id="d" tabindex="7" readonly>
<textarea rows="7" id="area" tabindex="8" class="form-control outtext" readonly></textarea>
I got error in console. It says $ is not a function. Please help me to solve this issue.
Please include this line during the HTML Render
function GetURLParams() {
var url = window.location.href;
var regex = /[?&]([^=#]+)=([^&#]*)/g,
params = {},
match;
while (match = regex.exec(url)) {
params[match[1]] = match[2];
}
return params;
}
var gcd2 = function(a, b, f) {
if( f )
{
if ( b<=1 )
return a;
}
else
{
if ( !b )
return a;
}
return gcd2(b, a % b, f);
};
$( document ).ready(function() {
var params = GetURLParams();
if (Object.keys(params).length > 0 && params.x != "") {
document.getElementById("x").value = params.x;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<input type="text" id="x" name="x" class="intext form-control" tabindex="1">
<button type="button" title="Convert" class="btn btn-lg btn-primary" tabindex="2" onclick="convert()"> Convert</button>
<input class="form-control" type="text" id="y" tabindex="5" readonly>
<input class="form-control" type="text" id="n" tabindex="6" readonly>
<canvas id="frac"></canvas>
<input class="form-control" type="text" id="d" tabindex="7" readonly>
<textarea rows="7" id="area" tabindex="8" class="form-control outtext" readonly></textarea>
Once you feel its fixed download the JQuery Package and save in your package
The probably simplest solution uses Fraction.js:
var f = new Fraction(0.182);
console.log(f.n, f.d); // 91, 500

check atleast 2 of 5 input fields were not empty

How to check of two out of five inputted fields and get the value? I'm using jQuery, and I'm not sure what is the proper positioning of this code. Maybe you guys can help me.
Here is my code:
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = "";
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
if (i >= 2) {
res = "Code Execution here";
}
}
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
The result that I get is that it only trigger the res variable if the execution reach into 2 above.
I want to submit the form only when there are at least two fields were inputted.
Thanks!
You're checking if any value other than the first two has value
The correct way to implement your check would be:
$(document).ready(function(){
$("#btnSubmit").on('click', function(){
var val = $(".validate");
var res = "";
var reqCount=0
for(var i = 0; i < val.length; i++){
if(val[i].value){
reqCount++;
}
if(reqCount >= 2){
res = "Code Execution here";
}
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
I don't know why there's a C# tag on this question, if you mean to do this on the server side, that'd be a whole different question
Change you logic to count number of filed having value in for loop
than base don count change alert message
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = ""; let count=0;
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
count++;
}
}
if (count >= 2) {
res = "Code Execution here";
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
If all you want to do is make sure you have atleast 2 feilds filled before the user submits the form , you can do the below:
function isEmpty(validateElem) {
return (validateElem === "" || typeof validateElem === 'undefined') ? true : false;
}
$(function(){
var InputValidateCount = 0;
$('form').submit(function(){
$('input').each(function(e , i){
if(!isEmpty($(this).val())) {
InputValidateCount++;
}
});
if(InputValidateCount < 2) {
return false; // Stop from from submitting;
}
});
});
You should count the validated fields before submission.
Upvote if this answered you. :P
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var minimumNonEmptyFields = 2;
var validatedNonEmptyFieldsCount = 0;
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
validatedNonEmptyFieldsCount++;
}
}
if(validatedNonEmptyFieldsCount >= minimumNonEmptyFields) {
alert( validatedNonEmptyFieldsCount + " fields are non-empty");
} else {
alert("Please fill " + (minimumNonEmptyFields - validatedNonEmptyFieldsCount) + " more fields");
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>
Validate any 2 input
</title>
</head>
<body>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<input type="text" class="validate" id="req6" name="req6">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
<script></script>
</body>
</html>
if atleast two input is not empty then return true else return false .
if return's true it submit's the form else it will not.
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = "";
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
if (i >= 2) {
res = "Code Execution here";
console.log("success");
return true;
}
}
}
console.log("fail");
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>

jQuery each function is not working and unable to create json string

I am trying create a json string. i have to get all element value from html with class and name. I am using jQuery
HTML
<div id="PackageBuilder-AddPax-Main">
<div class="PackageBuilder-AddPax">
<div>
<input type="text" name="input1" value="A1">
<div class="HotelSearchFrom-div-input2">
<input type="text" name="input2" value="1">
<input type="text" name="input2" value="2">
</div>
</div>
</div>
<div class="PackageBuilder-AddPax">
<div>
<input type="text" name="input1" value="A2">
<div class="HotelSearchFrom-div-input2">
<input type="text" name="input2" value="3">
<input type="text" name="input2" value="4">
</div>
</div>
</div>
<div class="PackageBuilder-AddPax">
<div>
<input type="text" name="input1" value="A3">
<div class="HotelSearchFrom-div-input2">
<input type="text" name="input2" value="5">
<input type="text" name="input2" value="6">
</div>
</div>
</div>
</div>
<input type="submit" onclick="Make_String()">
I have to make string like this but i am not be able to make it.
[{"Input1":A1,"Input2":[1,2]},{"Input1":A2,"Input2":[3,4]},{"Input1":A3,"Input2":[5,6]}]
Below Code i am using
function Make_String(){
var RoomGuests = [];
var j = 0;
$('#PackageBuilder-AddPax-Main').find('[name="input1"]').each(function(i){
var NoOfAdults_Val = $('[name="input1"]').val()
var input2array = [];
$('#HotelSearchFrom-div-input2').find('[name="input2"]').each(function() {
alert($(this).val());
input2array.push($(this).val());
});
RoomGuests[j] = [];
RoomGuests[j]['Input1'] = NoOfAdults_Val;
RoomGuests[j]['Input2'] = input2array;
j++
});
}
You can do with jQuery each() and map().
each() Method
function Make_String() {
array = [];
$('.PackageBuilder-AddPax').each(function(i,e) {
$(this).find('.HotelSearchFrom-div-input2').each(function(i,e) {
inputarray2 = [];
$(this).find('[name="input2"]').each(function(i,e) {
inputarray2.push($(e).val());
})
})
str = {
'Input1': $(this).find('[name="input1"]').val(),
'Input2': inputarray2
}
array.push(str);
});
console.log(array);
var jsonstring = JSON.stringify(array);
console.log(jsonstring);
}
OR
map() Method
function Make_String() {
var array = $('.PackageBuilder-AddPax').map(function() {
return {
'Input1': $(this).find('[name="input1"]').val(),
'Input2': $(this).find('[name="input2"]').map(function() {
return this.value;
}).get()
}
}).get();
console.log(array);
var jsonstring = JSON.stringify(array);
console.log(jsonstring);
}
The easiest way to achieve this would be to build an object in the required format and then run that through JSON.stringify. To build the object you can use map(), like this:
$('#submit').click(function() {
var obj = $('.PackageBuilder-AddPax').map(function() {
return {
'Input1': $(this).find('[name="input1"]').val(),
'Input2': $(this).find('[name="input2"]').map(function() {
return this.value;
}).get()
}
}).get();
var json = JSON.stringify(obj);
console.log(json);
});
Working example
Note that I amended the click handler so that it's attached using unobtrusive javascript, as on* event attributes are very outdated and should be avoided where possible.
function Make_String() {
var final = {};
$('.PackageBuilder-AddPax').each(function() {
$input = $(this).find($('[name="input2"]'));
var obj = {};
var arr = [];
$input.each(function() {
arr.push($(this).val());
})
final[$(this).find($('[name="input1"]')).val()] = arr;
})
console.log(final)
}
function Make_String() {
var final = [];
$('.PackageBuilder-AddPax').each(function() {
$input = $(this).find($('[name="input2"]'));
var obj = {};
var arr = [];
$input.each(function() {
arr.push($(this).val());
})
obj.input1 = $(this).find($('[name="input1"]')).val();
obj.input2 = arr;
final.push(obj);
})
console.log(final)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="PackageBuilder-AddPax-Main">
<div class="PackageBuilder-AddPax">
<div>
<input type="text" name="input1" value="A1">
<div class="HotelSearchFrom-div-input2">
<input type="text" name="input2" value="1">
<input type="text" name="input2" value="2">
</div>
</div>
</div>
<div class="PackageBuilder-AddPax">
<div>
<input type="text" name="input1" value="A2">
<div class="HotelSearchFrom-div-input2">
<input type="text" name="input2" value="3">
<input type="text" name="input2" value="4">
</div>
</div>
</div>
<div class="PackageBuilder-AddPax">
<div>
<input type="text" name="input1" value="A3">
<div class="HotelSearchFrom-div-input2">
<input type="text" name="input2" value="5">
<input type="text" name="input2" value="6">
</div>
</div>
</div>
</div>
<input type="submit" onclick="Make_String()">

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()
);

Categories