How to serialize a form in custom key/value pairs? - javascript

I need to serialize a form in a custom key/value pair format. This is how my HTML code looks like:
<form name="ltq_frm" id="ltq_frm">
<table class="table" id="licenses_to_quote">
<thead>
<tr>
<th>License ID</th>
<th>Quote ID</th>
<th>Agreement Type</th>
<th>Customer Site</th>
</tr>
</thead>
<tbody id="licenses_to_quote_body">
<tr data-id="96">
<td>
96
<input type="hidden" name="license_id" value="96">
</td>
<td>
<input class="hidden-select2-96" type="hidden" name="quote_id" value="249"> 249
</td>
<td>Percentage Support</td>
<td>Frito-Lay, Inc.</td>
</tr>
<tr data-id="100">
<td>
100
<input type="hidden" name="license_id" value="100">
</td>
<td>
<input class="hidden-select2-100" type="hidden" name="quote_id" value="">
</td>
<td>Percentage Support</td>
<td>Frito-Lay, Inc.</td>
</tr>
</tbody>
</table>
</form>
<button id="subm">
Click
</button>
And this is how I am serializing it:
$(function() {
$('#subm').click(function() {
var sA = $('#ltq_frm').serializeArray();
var s = $('#ltq_frm').serialize();
console.log(sA);
console.log(s);
});
});
This is "working" but I am getting an array of four values as output. I would like to get something like:
[
'license_id' => 'quote_id'
]
Using the example above:
[
96 => 249,
100 =>
]
The values above comes from the hidden elements on the form, those named as license_id and quote_id.
I was checking here but I couldn't get the idea in how to transform my values into the needed key/value pairs.
This is a jsFiddle I was working with in case you need it.
Note: this is a code in development so if you have a better suggestion or need to give me something different go ahead

You could manually map each row, get the two inputs, use the first as the key and the second as the value, like this
var result = $('#ltq_frm tbody tr').map(function() {
var inp = $('input', this), o = {};
o[inp.first().val()] = inp.last().val();
return o;
}).get();
FIDDLE

I get it. You need a custom code like this to do it:
var finalObj = { };
$.each(​$('form')​.serializeArray()​, function() {
finalObj[this.name] = this.value;
})​;
console.log(finalObj);
Snippet
var finalObj = { };
$.each($('form').serializeArray(), function() {
finalObj[this.name] = this.value;
});
console.log(finalObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="ltq_frm" id="ltq_frm">
<table class="table" id="licenses_to_quote">
<thead>
<tr>
<th>License ID</th>
<th>Quote ID</th>
<th>Agreement Type</th>
<th>Customer Site</th>
</tr>
</thead>
<tbody id="licenses_to_quote_body">
<tr data-id="96">
<td>
96
<input type="hidden" name="license_id" value="96">
</td>
<td>
<input class="hidden-select2-96" type="hidden" name="quote_id" value="249"> 249
</td>
<td>Percentage Support</td>
<td>Frito-Lay, Inc.</td>
</tr>
<tr data-id="100">
<td>
100
<input type="hidden" name="license_id[]" value="100">
</td>
<td>
<input class="hidden-select2-100" type="hidden" name="quote_id[]" value="">
</td>
<td>Percentage Support</td>
<td>Frito-Lay, Inc.</td>
</tr>
</tbody>
</table>
</form>
Update: To get your custom way, I need to still change it further. In your question, the code has some inconsistencies. Those I corrected are as follows:
license_id[] to license_id.
quote_id[] to quote_id.
Please follow one single convention.
var finalObj = { };
var lastLID = "";
$.each($('form').serializeArray(), function() {
if (this.name == "license_id")
lastLID = this.value;
else (this.name == "quote_id")
finalObj[lastLID] = this.value;
});
console.log(finalObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="ltq_frm" id="ltq_frm">
<table class="table" id="licenses_to_quote">
<thead>
<tr>
<th>License ID</th>
<th>Quote ID</th>
<th>Agreement Type</th>
<th>Customer Site</th>
</tr>
</thead>
<tbody id="licenses_to_quote_body">
<tr data-id="96">
<td>
96
<input type="hidden" name="license_id" value="96">
</td>
<td>
<input class="hidden-select2-96" type="hidden" name="quote_id" value="249"> 249
</td>
<td>Percentage Support</td>
<td>Frito-Lay, Inc.</td>
</tr>
<tr data-id="100">
<td>
100
<input type="hidden" name="license_id" value="100">
</td>
<td>
<input class="hidden-select2-100" type="hidden" name="quote_id" value="">
</td>
<td>Percentage Support</td>
<td>Frito-Lay, Inc.</td>
</tr>
</tbody>
</table>
</form>

Related

value store in Angularjs Objects and outputting in View

I have a form. It contains Name , quantity & price . I want to get input from form and store in Angularjs Objects. Then i have to output to View the whole array of angular objects. I tried with Angular Array it worked but to show in table ng-repeat not work . So i have to use Objects and output in table
CODE
Form
<div class="leftDev">
<h1>Enter New Product</h1>
<Table>
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" name="naam" ng-model="naam"> </td>
</tr>
<tr>
<td><label for="quantity">Quantity:</label></td>
<td><input type="number" name="quantity" ng-model="quantity"> </td>
</tr>
<tr>
<td><label for="price">Price:</label></td>
<td><input type="text" name="price" ng-model="price"> </td>
</tr>
<tr>
<td></td>
<td><button ng-click='push()'>ADD</button></td>
</tr>
</Table>
OUTPUT Table
<div class="rightDev">
<table border="2">
<tr>
<th>
Name
</th>
<th>
Quantity
</th>
</tr>
<tr ng-repeat="" >
<td >
</td>
<td >
</td>
</tr>
</table>
</div>
Script
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>
var myApp = angular.module("myApp",[]);
myApp.controller('myCtrl',function($scope){
$scope.items={
name:"jay",quantity:"100",price:"200"
};
$scope.push = function(){
$scope.items.name.push($scope.naam);
$scope.items.quantity.push($scope.quantity);
$scope.items.price.push($scope.price);
}
})
</script>
So , please show me right way to do it.
myApp.controller('myCtrl',function($scope){
$scope.list = [];
$scope.item = {
name:"jay",quantity:"100",price:"200"
};
$scope.push = function(){
$scope.list.push($scope.item);
$scope.item = {};
}
})
<h1>Enter New Product</h1>
<Table>
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" name="name" ng-model="item.name"> </td>
</tr>
<tr>
<td><label for="quantity">Quantity:</label></td>
<td><input type="number" name="quantity" ng-model="item.quantity"> </td>
</tr>
<tr>
<td><label for="price">Price:</label></td>
<td><input type="text" name="price" ng-model="item.price"> </td>
</tr>
<tr>
<td></td>
<td><button ng-click='push()'>ADD</button></td>
</tr>
</Table>
<div class="rightDev">
<table border="2">
<tr>
<th>
Name
</th>
<th>
Quantity
</th>
</tr>
<tr ng-repeat="obj in list" >
<td >
{{obj.name}}
</td>
<td >
{{obj.quantity}}
</td>
</tr>
</table>
</div>

How do I sum all columns in a table with the same classname in JavaScript?

I am trying to sum a price in a table, all the prices in the <td> have the same class name and I'd like to sum them up on a button click. I would eventually like to calculate the quantity into the total as well. This is what I have so far:
function sumAmounts() {
var sum = 0;
var listPriceTotal = $('.txtListPrice').each(function() {
sum += parseFloat($(this).html); // Or this.innerHTML, this.innerText
});
document.getElementById("txtTotal").value = listPriceTotal;
}
document.getElementById("addTotals").addEventListener("click", () => {
sumAmounts();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<th><label>SKU</label></th>
<th><label>Retail Price</label></th>
<th><label>List Price</label></th>
<th><label>Product Name</label></th>
<th><label>Quantity</label></th>
</tr>
<tr>
<td class="txtSKU">1234</td>
<td class="txtRetailPrice">12.50</td>
<td class="txtListPrice">11.75</td>
<td class="txtProductName">product 1</td>
<td class="txtQuantity"><input type="text"> </td>
</tr>
<tr>
<td class="txtSKU">12222</td>
<td class="txtRetailPrice">14.50</td>
<td class="txtListPrice">9.75</td>
<td class="txtProductName">product 2</td>
<td class="txtQuantity"><input type="text"> </td>
</tr>
<tfoot>
<th><label id="lblTotal">Total:</label><input type="text" name="txtTotal" id="txtTotal">
<input type="button" value="Add" id="addTotals">
</th>
</tfoot>
</table>
There's two issues in your code. Firstly you're trying to set a jQuery object as the value of the input, which is why you see [Object object] in the field. You need to set the value to sum.
The second issue is that you're supplying the html method reference to parseFloat(), not the actual html() value. With both of those addressed, the code works:
function sumAmounts() {
var sum = 0;
$('.txtListPrice').each(function() {
sum += parseFloat($(this).html());
});
document.getElementById("txtTotal").value = sum;
}
document.getElementById("addTotals").addEventListener("click", () => {
sumAmounts();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<th><label>SKU</label></th>
<th><label>Retail Price</label></th>
<th><label>List Price</label></th>
<th><label>Product Name</label></th>
<th><label>Quantity</label></th>
</tr>
<tr>
<td class="txtSKU">1234</td>
<td class="txtRetailPrice">12.50</td>
<td class="txtListPrice">11.75</td>
<td class="txtProductName">product 1</td>
<td class="txtQuantity"><input type="text"> </td>
</tr>
<tr>
<td class="txtSKU">12222</td>
<td class="txtRetailPrice">14.50</td>
<td class="txtListPrice">9.75</td>
<td class="txtProductName">product 2</td>
<td class="txtQuantity"><input type="text"> </td>
</tr>
<tfoot>
<th>
<label id="lblTotal">Total:</label>
<input type="text" name="txtTotal" id="txtTotal">
<input type="button" value="Add" id="addTotals">
</th>
</tfoot>
</table>

javascript get/store data from table

I'm trying to catch the data based on the id's after clicking the button (like store them) in order to use it for inserting needed id's afterwards into the DB. The js written is not working as expected, any ideas what is missing? Thank you for the support.
<script>
function goo() {
idprod=$("#idprod").val();
nprod=$("#nprod").val();
lastprod=$("#lastprod").val();
solarprod=$("#solarprod").val();
locprod=$("#locprod").val()
}
</script>
<form name="goo" method="post">
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Lastname</th>
<th>WK_Solar</th>
<th>Location</th>
<th>Save</th>
</tr>
<tr>
<td id="idprod">P1</td>
<td id="nprod">James</td>
<td id="lastprod">Lee</td>
<td id="solarprod">$1555</td>
<td id="locprod">Queens</td>
<td><input type="hidden" name="active" value="active"><input type="submit" name="submit" value="goo"></td>
</tr>
<tr>
<td id="idprod">P2</td>
<td id="nprod">Marc</td>
<td id="lastprod">Hoobs</td>
<td id="solarprod">$955</td>
<td id="locprod">Bronx</td>
<td><input type="hidden" name="active" value="active"><input type="submit" name="submit" value="goo"></td>
</tr>
</table>
</form>
1- You are using val which is the attr Value. you should use html() or text() to get the value.
2- You have two rows, you should browse those two rows and get the data from each row
function goo() {
var firstRow = $(".test tbody tr").last();
idprod=firstRow.find("#idprod").html();
nprod=firstRow.find("#nprod").html();
lastprod=firstRow.find("#lastprod").html();
solarprod=firstRow.find("#solarprod").html();
locprod=firstRow.find("#locprod").html()
console.log(idprod)
}
$(document).ready(function(){
goo();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="goo" method="post">
<table border="1" class="test">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Lastname</th>
<th>WK_Solar</th>
<th>Location</th>
<th>Save</th>
</tr>
</thead>
<tr>
<td id="idprod">P1</td>
<td id="nprod">James</td>
<td id="lastprod">Lee</td>
<td id="solarprod">$1555</td>
<td id="locprod">Queens</td>
<td><input type="hidden" name="active" value="active"><input type="submit" name="submit" value="goo"></td>
</tr>
<tr>
<td id="idprod">P2</td>
<td id="nprod">Marc</td>
<td id="lastprod">Hoobs</td>
<td id="solarprod">$955</td>
<td id="locprod">Bronx</td>
<td><input type="hidden" name="active" value="active"><input type="submit" name="submit" value="goo"></td>
</tr>
</table>
</form>

Total value with jquery on table

I tried to calculate the total on the table using jquery, but when run totals do not appear. so I want to show the total live when I enter the input value, total auto-summing, what's wrong?
HTML
<table class="table table-condensed">
<thead>
<tr>
<td class="text-left"><strong>Product</strong></td>
<td class="text-center"><strong>Value</strong></td>
</tr>
</thead>
<tbody>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_a" name="producta" value="12.000"></td>
</tr>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_b" name="producta" value="19.000"></td>
</tr>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_c" name="producta" value="15.000"></td>
</tr>
<tr>
<td class="thick-line"><strong>Total</strong></td>
<td class="thick-line"><input type="text" id="total" name="total" /></td>
</tr>
</tbody>
</table>
JS
jQuery(document).ready(function(){
var total = ($('#product_a').val() + $('#product_b').val() + $('#product_c').val()) ;
$('#total').val(total);
});
You're doing it wrong. val() returns a string on an input[type=text] and currently you're just concatenating string values.
I want to show the total live when I enter the input value
Then, you need to add a listener when the inputs are being changed as you type. This could be done with keyup event.
E.g.
$(function() {
var $aProduct = $('#product_a'),
$bProduct = $('#product_b'),
$cProduct = $('#product_c'),
$total = $('#total'),
runTotal = function() {
var a = parseInt($aProduct.val()),
b = parseInt($bProduct.val()),
c = parseInt($cProduct.val());
$total.val(a + b + c);
};
$('.inputVal').on('keyup', runTotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed">
<thead>
<tr>
<td class="text-left"><strong>Product</strong>
</td>
<td class="text-center"><strong>Value</strong>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_a" name="producta" class="inputVal" value="12.000">
</td>
</tr>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_b" name="productb" class="inputVal" value="19.000">
</td>
</tr>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_c" name="productc" class="inputVal" value="15.000">
</td>
</tr>
<tr>
<td class="thick-line"><strong>Total</strong>
</td>
<td class="thick-line">
<input type="text" id="total" name="total" />
</td>
</tr>
</tbody>
</table>
Hi try following code....
jQuery(document).ready(function(){
$("input").on("change",updateTotal); // this will total on change input.
updateTotal(); //this will total on start..
});
function updateTotal()
{
var total = ($('#product_a').val()*1 + $('#product_b').val()*1 + $('#product_c').val()*1) ;
//By multiplying 1 to any string format number it will convert to number datatype.
//var total = (Number($('#product_a').val()) + Number($('#product_b').val()) + Number($('#product_c').val()));
//You can also uncomment above line to get your desire output.
$('#total').val(total);
}

How to switch decimal and rounded whole number using javascript

I have a table that renders data from my Django app which uses PostgreSQL database. How would I add a button to switch the Score column so it'll display the numbers between its original decimal value and rounded whole numbers?
Here is an example of what it would look like: https://jsfiddle.net/8a66gtww/
<table class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th class="track_id"><input id="checkAll" type="checkbox" /></th>
<th>First Name</th>
<th>Last Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td class="track_id"><input type="checkbox" name="track_id" value="2" /></td>
<td>John</td>
<td>Do</td>
<td>65.85</td>
</tr>
<tr class="even">
<td class="track_id"><input type="checkbox" name="track_id" value="1" /></td>
<td>Michael</td>
<td>Smith</td>
<td>88.25</td>
</tr>
<tr class="odd">
<td class="track_id"><input type="checkbox" name="track_id" value="4" /></td>
<td>Donald</td>
<td>James</td>
<td>120.11</td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
<br />
<button onclick="myFunction()">Switch</button> // Switches score between decimal and rounded whole number
See if it helps. I just modified your html a little for storing your score values so it can undo the round.
<table class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th class="track_id"><input id="checkAll" type="checkbox" /></th>
<th>First Name</th>
<th>Last Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td class="track_id"><input type="checkbox" name="track_id" value="2" /></td>
<td>John</td>
<td>Do</td>
<td>65.85</td>
<input type="hidden" value="65.85">
</tr>
<tr class="even">
<td class="track_id"><input type="checkbox" name="track_id" value="1" /></td>
<td>Michael</td>
<td>Smith</td>
<td>88.25</td>
<input type="hidden" value="88.25">
</tr>
<tr class="odd">
<td class="track_id"><input type="checkbox" name="track_id" value="4" /></td>
<td>Donald</td>
<td>James</td>
<td>120.11</td>
<input type="hidden" value="120.11">
</tr>
</tbody>
<tfoot></tfoot>
</table>
<br />
<button class="switch">Switch</button>
and jquery is:
$('.switch').click(function () {
$('.table tbody tr td:nth-child(4)').each(function() {
if ($(this).html().indexOf('.') >= 0) {
$(this).html(Math.round($(this).html()));
} else {
$(this).html($(this).parent().find('input[type=hidden]').val());
}
});
});
It verifies if your score has the decimal dot. If the score is decimal, then it rounds it. If the score isn't decimal, it restores the original value.
https://jsfiddle.net/jdm3eovz/
Here's something to get you started:
<script>
window.switcher = {
johnsScore: 0
}
switcher.switch = function(){
var $johnsScore = $('tbody > tr td').eq(3)
var $johnsCheckbox = $('tbody > tr input')
if ($johnsCheckbox.prop('checked')) {
if (this.johnsScore > 0) {
$johnsScore.text(this.johnsScore)
this.johnsScore = 0
}
else {
this.johnsScore = $johnsScore.text()
$johnsScore.text(Math.round(this.johnsScore))
}
}
}
</script>
The button then changes to:
<button onclick="switcher.switch()">Switch</button>

Categories

Resources