Decimal to Fraction Calculator Javascript Issue - javascript

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

Related

form validation with data ranges

I am trying to validate HTML form. check a field with two other relative range fields. I want to check all variables isset and between the range before submitting form.
I tried this method not giving the expected result.
How can I do it with other easiest method.
$("#form").submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
var apple = $('.apple').val();
var aFirst = $('.aFirst').val();
var aLast = $('.aLast').val();
var banana = $('.banana').val();
var bFirst = $('.bFirst').val();
var bLast = $('.bLast').val();
var orange = $('.orange').val();
var oFirst = $('.oFirst').val();
var oLast = $('.oLast').val();
if(apple >= aFirst && apple <= aLast){
var a = 'true';
}else{
var a = 'false';
}
if(banana >= bFirst && banana <= bLast){
var b = 'true';
}else{
var b = 'false';
}
if(orange >= oFirst && orange <= oLast){
var o = 'true';
}else{
var o = 'false';
}
if(a == 'true' && b == 'true' && o == 'true')
{
alert('success');
//do ajax
}else{
alert('error');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="form-group col-md-12">
<label>Apple Price:</label>
<input type="number" class="apple" placeholder="Type between 15-25">
<input type="hidden" class="aFirst" value="10">
<input type="hidden" class="aLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Banana Price:</label>
<input type="number" class="banana" placeholder="Type between 10-20">
<input type="hidden" class="bFirst" value="10">
<input type="hidden" class="bLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Orange Price:</label>
<input type="number" class="orange" placeholder="Type between 10-20">
<input type="hidden" class="oFirst" value="10">
<input type="hidden" class="oLast" value="20">
</div>
<button type="submit" id="submit">Submit</button>
</form>
The hidden input classes for apples should be aFirst and aLast:
Update: I have corrected the following line:
<input type="hidden" class="aLast" value="25">
Update 2: Works when fruit divs are removed. + Cleanup.
$("#form").submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var apple = $('.apple').val();
var aFirst = $('.aFirst').val();
var aLast = $('.aLast').val();
var banana = $('.banana').val();
var bFirst = $('.bFirst').val();
var bLast = $('.bLast').val();
var orange = $('.orange').val();
var oFirst = $('.oFirst').val();
var oLast = $('.oLast').val();
var a = true;
var b = true;
var o = true;
if (apple == "" || apple < aFirst || apple > aLast) {
a = false;
}
if (banana == "" || banana < bFirst || banana > bLast) {
b = false;
}
if (orange == "" || orange < oFirst || orange > oLast) {
o = false;
}
if (a && b && o) {
alert('success');
//do ajax
} else {
alert('error');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="form-group col-md-12">
<label>Banana Price:</label>
<input type="number" class="banana" placeholder="Type between 10-20">
<input type="hidden" class="bFirst" value="10">
<input type="hidden" class="bLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Orange Price:</label>
<input type="number" class="orange" placeholder="Type between 10-20">
<input type="hidden" class="oFirst" value="10">
<input type="hidden" class="oLast" value="20">
</div>
<button type="submit" id="submit">Submit</button>
</form>
There is a typo,
you have a class name as qFirst and qLast in HTML and js you have written .aFirst and .aLast.
Also convert all values to Number.
When you do .val(), it returns string. And Comparing Strings can give unexpected results
$("#form").submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
var apple = Number($('.apple').val());
var aFirst = Number($('.aFirst').val());
var aLast = Number($('.aLast').val());
var banana = Number($('.banana').val());
var bFirst = Number($('.bFirst').val());
var bLast = Number($('.bLast').val());
var orange = Number($('.orange').val());
var oFirst = Number($('.oFirst').val());
var oLast = Number($('.oLast').val());
if(apple >= aFirst && apple <= aLast){
var a = 'true';
}else{
var a = 'false';
}
if(banana >= bFirst && banana <= bLast){
var b = 'true';
}else{
var b = 'false';
}
if(orange >= oFirst && orange <= oLast){
var o = 'true';
}else{
var o = 'false';
}
if(a == 'true' && b == 'true' && o == 'true')
{
alert('success');
//do ajax
}else{
alert('error');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="form-group col-md-12">
<label>Apple Price:</label>
<input type="number" class="apple" placeholder="Type between 15-25">
<input type="hidden" class="aFirst" value="10">
<input type="hidden" class="aLast" value="25">
</div>
<div class="form-group col-md-12">
<label>Banana Price:</label>
<input type="number" class="banana" placeholder="Type between 10-20">
<input type="hidden" class="bFirst" value="10">
<input type="hidden" class="bLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Orange Price:</label>
<input type="number" class="orange" placeholder="Type between 10-20">
<input type="hidden" class="oFirst" value="10">
<input type="hidden" class="oLast" value="20">
</div>
<button type="submit" id="submit">Submit</button>
</form>

Calculation use key up function with a thousand separator format

i want to make a calculation when user key in, the result will show in other field. with format number with thousand separator like 2,500.00
so if i sum 2,500.00 + 2,500.00 the result must be 5,000.00
but my code show 4.00
function isNumberKey(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
if (key.length == 0) return;
var regex = /^[0-9.,\b]+$/;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
function toFloat(z) {
var x = document.getElementById(z);
x.value = parseFloat(x.value).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
$( ".fn" ).keyup(function() {
var nmi = $('#nmi').val();
var a = $('#a').val();
var total = parseFloat(nmi) + parseFloat(a);
$("#total").val(parseFloat(total).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input onchange="toFloat('nmi')" type="text" maxlength="10" onkeypress="return isNumberKey(event)" required="required" class="form-control fn" placeholder="RM" name="nmi" id="nmi">
<input onchange="toFloat('a')" type="text" maxlength="10" onkeypress="return isNumberKey(event)" required="required" class="form-control fn" placeholder="RM" name="a" id="a">
<br> total
<input onchange="toFloat('total')" type="text" maxlength="10" onkeypress="return isNumberKey(event)" required="required" class="form-control fn" placeholder="RM" name="total" id="total">
Lets try this one,,, thats works for me "Dial Gtg"
$('input.CurrencyInput').on('blur', function() {
const value = this.value.replace(/,/g, '');
this.value = parseFloat(value).toLocaleString('en-US', {
style: 'decimal',
maximumFractionDigits: 2,
minimumFractionDigits: 2
});
});
$('input.CurrencyInput2').on('blur', function() {
const value = this.value.replace(/,/g, '');
this.value = parseFloat(value).toLocaleString('en-US', {
style: 'decimal',
maximumFractionDigits: 2,
minimumFractionDigits: 2
});
});
$( ".fn" ).keyup(function() {
var a = $('#a').val().replace(/,/g,'');
var b = $('#b').val().replace(/,/g,'');
var total = parseFloat(a) + parseFloat(b);
$("#total_nya").val(parseFloat(total).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="CurrencyInput fn" id="a">
<input class="CurrencyInput2 fn" id="b">
<input class="total_nya" id="total_nya">
When parseFloat('2,500.00') will return 2 because of ,.
parseFloat: parses its argument, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters
remove , from value by using replace()
function isNumberKey(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
if (key.length == 0) return;
var regex = /^[0-9.,\b]+$/;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
function toFloat(z) {
var x = document.getElementById(z);
x.value = parseFloat(x.value).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
$( ".fn" ).keyup(function() {
var nmi = $('#nmi').val().replace(/,/g,'');
var a = $('#a').val().replace(/,/g,'');
var total = parseFloat(nmi) + parseFloat(a);
$("#total").val(parseFloat(total).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input onchange="toFloat('nmi')" type="text" maxlength="10" onkeypress="return isNumberKey(event)" required="required" class="form-control fn" placeholder="RM" name="nmi" id="nmi">
<input onchange="toFloat('a')" type="text" maxlength="10" onkeypress="return isNumberKey(event)" required="required" class="form-control fn" placeholder="RM" name="a" id="a">
<br> total
<input onchange="toFloat('total')" type="text" maxlength="10" onkeypress="return isNumberKey(event)" required="required" class="form-control fn" placeholder="RM" name="total" id="total">
Simple for your change in code.
$(document).ready(function() {
$('.fn').on('input', function() {
this.value = this.value.match(/^\d+\.?\d{0,2}/);
calculate();
});
});
function calculate() {
var t = 0;
nmi = ($("#nmi").val() ? parseFloat($("#nmi").val()) : 0);
a = ($("#a").val() ? parseFloat($("#a").val()) : 0);
$("#total").val(nmi + a);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" maxlength="10" required="required" class="form-control fn" placeholder="RM" name="nmi" id="nmi">
<input type="text" maxlength="10" required="required" class="form-control fn" placeholder="RM" name="a" id="a">
<br> total
<input type="text" maxlength="10" required="required" class="form-control fn" placeholder="RM" name="total" id="total">

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>

Trying to make a form to calculate compounded interest

I've found different types of snippets on here calculating interest and so forth but unable to find the help I need.
I'm making a simple form and using Javascript to find the compounded interest and output it in HTML.
I've used the getDocumentById with and without the innerHTML as well as placing it in parseInt(). Long story short, I get 'NaN' as output.
Take a look at what I finished up with and maybe someone can point me as to what I might be missing. Thanks
<form onsubmit="return false">
<input id="a" name="a" type="number" step="any" placeholder="Present Value"> * (
<input id="b" name="b" type="number" step="any" placeholder="Number of years"> +
<input id="c" name="c" type="number" step="any" placeholder="Interest Rate">)^
<input id="d" name="d" type="number" step="any" placeholder="N number of Years">=
<button onclick="futureNyears()">Answer</button>
<p id="futureNanswer"></p>
</form>
<script type="text/javascript">
function futureNyears() {
var a = parseInt(document.getElementById('a'));
var b = parseInt(document.getElementById('b'));
var c = parseFloat(document.getElementById('c'));
var d = parseInt(document.getElementById('d'));
var E = eval(b+c);
var r = Math.pow(E, d);
var f = eval(E * r);
var g = f.toString();
document.getElementById("futureNanswer").innerHTML = g;
}
</script>
After getting element by ID, you need to access the value attribute, parseInt received DOM object which equated to NaN all time.
function futureNyears() {
var a = parseInt(document.getElementById('a').value);
var b = parseInt(document.getElementById('b').value);
var c = parseFloat(document.getElementById('c').value);
var d = parseInt(document.getElementById('d').value);
var E = (b+c);
var r = Math.pow(E, d);
var f = (E * r);
var g = f.toString();
document.getElementById("futureNanswer").innerHTML = g;
}
<form onsubmit="return false">
<input id="a" name="a" type="number" step="any" placeholder="Present Value"> * (
<input id="b" name="b" type="number" step="any" placeholder="Number of years"> +
<input id="c" name="c" type="number" step="any" placeholder="Interest Rate">)^
<input id="d" name="d" type="number" step="any" placeholder="N number of Years">=
<button onclick="futureNyears()">Answer</button>
<p id="futureNanswer"></p>
</form>
document.getElementById('a') return the dom element so you have to get the value out of it like below
var a = parseInt(document.getElementById('a').value);
In your case you forgot to write document.getElementById('a').value() because its a form element and you cannot extract its value without value() attribute.
Parseint() always return the first number detected in your string .
You need to use the .value property to return the value of the particular element.
var a = parseInt(document.getElementById('a').value);
The value property sets or returns the value of the option (the value to be sent to the server when the form is submitted)
HTML
<!DOCTYPE html>
<html>
<head>
<title>CI</title>
</head>
<body>
<form onsubmit="return false">
<input id="a" name="a" type="number" step="any" placeholder="Present Value"> * (
<input id="b" name="b" type="number" step="any" placeholder="Number of years"> +
<input id="c" name="c" type="number" step="any" placeholder="Interest Rate">)^
<input id="d" name="d" type="number" step="any" placeholder="N number of Years">=
<button onclick="futureNyears()">Answer</button>
<p id="futureNanswer"></p>
</form>
</body>
</html>
JavaScript
<script type="text/javascript">
function futureNyears() {
var a = parseInt(document.getElementById('a').value);
var b = parseInt(document.getElementById('b').value);
var c = parseFloat(document.getElementById('c').value);
var d = parseInt(document.getElementById('d').value);
var E = eval(b+c);
var r = Math.pow(E, d);
var f = eval(E * r);
var g = f.toString();
document.getElementById("futureNanswer").innerHTML = g;
}
</script>
In order to get a value from input text box use
var a = parseInt(document.getElementById('a').value);
instead of
var a = parseInt(document.getElementById('a'));
<form onsubmit="return false">
<input id="a" name="a" type="number" step="any" placeholder="Present Value"> * (
<input id="b" name="b" type="number" step="any" placeholder="Number of years"> +
<input id="c" name="c" type="number" step="any" placeholder="Interest Rate">)^
<input id="d" name="d" type="number" step="any" placeholder="N number of Years">=
<button onclick="futureNyears()">Answer</button>
<p id="futureNanswer"></p>
</form>
<script type="text/javascript">
function futureNyears() {
var a = parseInt(document.getElementById('a').value);
var b = parseInt(document.getElementById('b').value);
var c = parseFloat(document.getElementById('c').value);
var d = parseInt(document.getElementById('d').value);
var E = eval(b+c);
var r = Math.pow(E, d);
var f = eval(E * r);
var g = f.toString();
document.getElementById("futureNanswer").innerHTML = g;
}
</script>

Convert form fields into JSON object

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"]
}
}
}

Categories