Boostrap Table How to add commas between numbers - javascript

Hi Have the following code which populates bootstrap table.
During the table generation how do I format and add "$" before the number
and any number should be displayed in this order $100,00,00.00 or $100,00.00 or $100.00
here is my code
$(function () {
$.getJSON("https://api.myjson.com/bins/89vsf", function (jsonFromFile) {
$('#table1').bootstrapTable({
data: jsonFromFile.rows
})
var data = $('#table1').bootstrapTable('getData');
var total1 = data.reduce(function(a, b){
return a + parseFloat(b.LongMarketValue.replace('$',''));
}, 0);
document.querySelector('.total1').innerHTML = total1;
});
});
HTML table
<table id="table1">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="Account">Account #</th>
<th data-field="ClientName">Client</th>
<th data-field="AccountType">Account Type</th>
<th data-field="MarketValue"> Market Value</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<th></th>
<th> Total <span class="total1"></span></th>
</tr>
</tfoot>
</table>
JSON
{
"Name": "Jie wn",
"Account": "C10",
"LoanApproved": "12/5/2015",
"LastActivity": "4/1/2016",
"PledgedPortfolio": "1000",
"MaxApprovedLoanAmt": "10000",
"LoanBalance": "1849000",
"AvailableCredit": "2877.824375",
"Aging": "3",
"Brokerage": "My Broker",
"Contact": "oJohnson",
"ContactPhone": "-3614",
"RiskCategory": "Yellow",
"rows": [{
"Account": "06-1234",
"ClientName": "S Smth",
"AccountType": "tail",
"LongMarketValue": "$40000"
}, {
"Account": "08-1235",
"ClientName": "all Sth",
"AccountType": "REV Trust",
"LongMarketValue": "$55000"
},
{
"Account": "086-1236",
"ClientName": "Sly Smith",
"AccountType": "Reail",
"LongMarketValue": "$5500"
}]
}

You could use toLocaleString() to convert number to currency format. Or use regular expression to do this, How to print a number with commas as thousands separators in JavaScript
Working example.
$(function () {
$.getJSON("https://api.myjson.com/bins/89vsf", function (jsonFromFile) {
var rows = jsonFromFile.rows.map(function(item){
item.LongMarketValue = parseFloat(item.LongMarketValue.replace('$',''));
item.LongMarketValue = getFormattedCurrency(item.LongMarketValue);
return item;
});
$('#table1').bootstrapTable({
data: rows
})
var data = $('#table1').bootstrapTable('getData');
var total1 = data.reduce(function(a, b){
return a + parseFloat(b.LongMarketValue.replace('$','').split(',').join(''));
}, 0);
document.querySelector('.total1').innerHTML = getFormattedCurrency(total1);
});
});
function getFormattedCurrency(number){
return number.toLocaleString('en-US',{style: 'currency', currency: 'USD'});
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="table1">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="Account">Account #</th>
<th data-field="ClientName">Client</th>
<th data-field="AccountType">Account Type</th>
<th data-field="LongMarketValue"> Market Value</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<th></th>
<th> Total <span class="total1"></span></th>
</tr>
</tfoot>
</table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://rawgit.com/wenzhixin/bootstrap-table/master/src/bootstrap-table.js"></script>
<script src="script.js"></script>
</body>
</html>
Working plunkr http://plnkr.co/edit/PSCR5iS7DSWkuQb1jv5P?p=preview
Hope this helps.

a couple of prototype functions that I use for this
String.prototype.toTwoDecimals = function () {
var value = this;
if (isNaN(value)) {
value = 0;
}
return parseFloat(Math.round(value * 100) / 100).toFixed(2);
};
String.prototype.toCommaSeperated = function () {
var value = this;
if (isNaN(value)) {
value = 0;
}
while (/(\d+)(\d{3})/.test(value.toString())) {
value = value.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
}
return value;
};
String.prototype.toUSD = function () {
var value = this;
if (isNaN(value)) {
value = 0;
}
return '$' + this.toString().toTwoDecimals().toCommaSeperated();
};
then you can use "10000".toCommaSeperated() or "100000".toUSD()

Related

Javascript calling API array handling with HTML

I am calling a BUS ETA api which it will return a json with ETA and route information. Example as below. I manage to get the first array to show in HTML but without success for the second [1] and third[2]. I manage to see all three ETA with console.log but won't show in HTML.
Any idea?
UPDATE : Created a jsFiddle example.
https://jsfiddle.net/21tk38b9/
BUS ETA API SAMPLE DATA
{
"type": "ETA",
"version": "1.0",
"generated_timestamp": "2021-06-29T16:02:53+08:00",
"data": [
{
"co": "KMB",
"route": "978",
"dir": "I",
"service_type": 1,
"seq": 7,
"dest_tc": "粉嶺(華明)",
"dest_sc": "粉岭(华明)",
"dest_en": "FANLING (WAH MING)",
"eta_seq": 1,
"eta": "2021-06-29T16:11:24+08:00",
"rmk_tc": "",
"rmk_sc": "",
"rmk_en": "",
"data_timestamp": "2021-06-29T16:02:41+08:00"
},
{
"co": "KMB",
"route": "978",
"dir": "I",
"service_type": 1,
"seq": 7,
"dest_tc": "粉嶺(華明)",
"dest_sc": "粉岭(华明)",
"dest_en": "FANLING (WAH MING)",
"eta_seq": 2,
"eta": "2021-06-29T16:28:15+08:00",
"rmk_tc": "原定班次",
"rmk_sc": "原定班次",
"rmk_en": "Scheduled Bus",
"data_timestamp": "2021-06-29T16:02:41+08:00"
},
{
"co": "KMB",
"route": "978",
"dir": "I",
"service_type": 1,
"seq": 7,
"dest_tc": "粉嶺(華明)",
"dest_sc": "粉岭(华明)",
"dest_en": "FANLING (WAH MING)",
"eta_seq": 3,
"eta": "2021-06-29T16:43:15+08:00",
"rmk_tc": "原定班次",
"rmk_sc": "原定班次",
"rmk_en": "Scheduled Bus",
"data_timestamp": "2021-06-29T16:02:41+08:00"
}
]
}
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mining Status</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/src/js/Untitled-4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="/src/css/main.css">
<link rel="stylesheet" href="/src/css/15.css">
<style type="text/css">
.fullscreen {
position: fixed;
overflow-y:fixed;
width: 100%;
}
</style>
</head>
<div id="wrap">
<body>
<div style="
font-size: 100px;
text-align: center;">
<div id="rmk"></div>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Route</th>
<th scope="col">ETA</th>
<th scope="col">Remark</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td><div id="route"></div></td>
<td><div id="but"></div>
</td>
<td></td>
</tr>
<tr>
<th scope="row">2</th>
<td></td>
<td><div id="but"></div>
<td></td>
</tr>
<tr>
<th scope="row">3</th>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</body>
</div>
</html>
Javascript
function repeat57() {
$(function() {
$.ajax({
type: "GET",
url: "https://data.etabus.gov.hk/v1/transport/kmb/eta/83B717529F9794BC/978/1",
dataType: "json",
success: function (data) {
console.log(typeof data); // -- Object
var json = data;
for (var i = 0; i < json.data.length; i++) {
var str = json.data[i].eta
if (str !== null ) {
str = str.split("T").pop();
str2 = str.split("+",1).pop();
str3 = str2.replace(/:/g,'');
d = new Date();
datetext = d.toTimeString();
datetext = datetext.split(' ')[0];
datetext = datetext.replace(/:/g,'');
console.log(datetext)
var eta = str3 - datetext;
console.log(eta)
var eta2 = "[ " + eta.toString().slice(0, -2) +" mins,]";
} else {
var remark = json.data[i].rmk_tc
eta2 = remark;
}
console.log(typeof str)
$('#but').html(eta2);
$('#rmk').html(remark);
}
}
});
});
setTimeout(repeat57, 19000);
}
repeat57();
function repeat58() {
$(function() {
$.ajax({
type: "GET",
url: "https://data.etabus.gov.hk/v1/transport/kmb/eta/83B717529F9794BC/978/1",
dataType: "json",
success: function (data) {
var json = data;
console.log(typeof .json)
for (var i = 0; i < json.data.length; i++) {
var str = JSON.parse(json.data[i].route)
if (str !== null ) {
} else {
var remark = json.data[i].rmk_tc
str = remark;
}
console.log(typeof str)
$('#route').html(str);
}
}
});
});
setTimeout(repeat58, 19000);
}
repeat58();
Do you want to be dynamic or are there always only 3 entries?
If there are three entries you could do:
HTML Code:
<head>
<meta charset="utf-8">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="rmk"></div>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Route</th>
<th scope="col">ETA</th>
<th scope="col">Remark</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>
<div class="route"></div>
</td>
<td>
<div class="but"></div>
</td>
<td></td>
</tr>
<tr>
<th scope="row">2</th>
<td>
<div class="route"></div>
</td>
<td>
<div class="but"></div>
</td>
<td></td>
</tr>
<tr>
<th scope="row">3</th>
<td>
<div class="route"></div>
</td>
<td>
<div class="but"></div>
</td>
<td></td>
</tr>
</tbody>
</table>
</body>
JavaScript:
function repeat57() {
$(function() {
$.ajax({
type: "GET",
url: "https://data.etabus.gov.hk/v1/transport/kmb/eta/83B717529F9794BC/978/1",
dataType: "json",
success: function(data) {
console.log(data); // -- Object
var json = data;
const buts = $('.but');
for (var i = 0; i < json.data.length; i++) {
var str = json.data[i].eta
if (str !== null) {
str = str.split("T").pop();
str2 = str.split("+", 1).pop();
str3 = str2.replace(/:/g, '');
d = new Date();
datetext = d.toTimeString();
datetext = datetext.split(' ')[0];
datetext = datetext.replace(/:/g, '');
console.log(datetext)
var eta = str3 - datetext;
var eta2 = eta.toString().slice(0, -2) + " mins";
} else {
var remark = json.data[i].rmk_tc
eta2 = remark;
}
$(buts[i]).html(eta2);
}
}
});
});
setTimeout(repeat57, 19000);
}
repeat57();
function repeat58() {
$(function() {
$.ajax({
type: "GET",
url: "https://data.etabus.gov.hk/v1/transport/kmb/eta/83B717529F9794BC/978/1",
dataType: "json",
success: function(data) {
var json = data;
console.log(json)
const routeElements = $('.route');
for (var i = 0; i < json.data.length; i++) {
var str = JSON.parse(json.data[i].route)
if (str !== null) {
} else {
var remark = json.data[i].rmk_tc
str = remark;
}
$(routeElements[i]).html(str);
}
}
});
});
setTimeout(repeat58, 19000);
}
repeat58();
Make sure to change the ids to classes (but, route, etc) and add it to all the rows where it is needed.
And when iterating through the result you pick the correct element via the index.
See the updated jsFiddle: https://jsfiddle.net/sgjx05qf/
This would be a solution if you always know the count of the result.

How to insert array values into a HTML table with javascript?

I am trying to put an array in a HTML table with javascript function but i dont khont how to insert this array? The idea is when i click on button Insert, it'll add one person's information into row.
This's my table
<script>
//Array
var a = [
{name:"Micheal", age:20, hometown:"New York"},
{name:"Santino", age:25, hometown:"Los Angeles"},
{name:"Fredo", age:29, hometown:"California"},
{name:"Hagen", age:28, hometown:"Long Beach"},
]
//Insert data function
function Insert_Data() {
var table = document.getElementById("myTable");
//Help......
}
</script>
<!--Button Insert-->
<input type="button" onclick="Insert_Data" value="Insert" />
<!--Table-->
<table id="myTable">
<tr>
<th>Full Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
You declare both thead and tbody and in function in loop fill the table
var a = [
{name:"Micheal", age:20, hometown:"New York"},
{name:"Santino", age:25, hometown:"Los Angeles"},
{name:"Fredo", age:29, hometown:"California"},
{name:"Hagen", age:28, hometown:"Long Beach"},
]
//Insert data function
function Insert_Data() {
var table = document.getElementById("datas");
table.innerHTML="";
var tr="";
a.forEach(x=>{
tr+='<tr>';
tr+='<td>'+x.name+'</td>'+'<td>'+x.age+'</td>'+'<td>'+x.hometown+'</td>'
tr+='</tr>'
})
table.innerHTML+=tr;
//Help......
}
<input type="button" onclick="Insert_Data()" value="Insert" />
<!--Table-->
<table id="myTable">
<thead>
<tr>
<th>Full Name</th>
<th>Age</th>
<th>Country</th>
</tr>
</thead>
<tbody id="datas">
</tbody>
</table>
Demo proof: https://jsfiddle.net/psw41g6k/
function Insert_Data() {
var table = document.getElementById("myTable");
var rows = table.querySelectorAll('tr');
console.log(rows)
for (let i = 1; i < rows.length; i++) {
rows[i].children[0].textContent = a[i-1].name
rows[i].children[1].textContent = a[i-1].age
rows[i].children[2].textContent = a[i-1].hometown
}
}
For dynamic tables if you gonna change your array frequently
let tableBody = a.reduce((rows, nextRow) =>{
return rows +=
'<tr>' +
Object.keys(nextRow).reduce((cols, nextCol) => {
return cols += '<th>' + nextRow[nextCol] + '</th>'
}, '') +
'</tr>'
}, '')
Create a dynamic element tr and td at the click of the button and append it to the table element in the document.
Use https://www.w3schools.com/jsref/met_node_appendchild.asp as a reference to understand how to create a dynamic element.
Here is a completely generic method, you can add a new key and it adds a new column to the data, no problem:
//Array
var myData = [
{name:"Micheal", age:20, hometown:"New York", example: "extra"},
{name:"Santino", age:25, hometown:"Los Angeles", example: "extra"},
{name:"Fredo", age:29, hometown:"California", example: "extra"},
{name:"Hagen", age:28, hometown:"Long Beach", example: "extra"},
]
//get references to the table and the head and body:
const myTable = document.getElementById('myTable');
const myTable_header = myTable.querySelector('thead')
const myTable_body = myTable.querySelector('tbody')
//Insert data function
function Insert_Data() {
//Help...... :
myTable_header.innerHTML = '';
var tr = document.createElement('tr');
const headers_data = Object.keys(myData[0]);
headers_data.forEach((key) => {
var th = document.createElement('th')
th.innerHTML = key
tr.appendChild(th);
})
myTable_header.appendChild(tr);
myTable_body.innerHTML = '';
for (let i = 0; i < myData.length; i++){
var tr = document.createElement('tr');
headers_data.forEach((key) => {
var td = document.createElement('td');
td.innerHTML = myData[i][key]
tr.appendChild(td);
});
myTable_body.appendChild(tr);
}
}
<!--Button Insert-->
<input type="button" onclick="Insert_Data()" value="Insert" />
<!--Table-->
<table id="myTable">
<thead>
<!-- Data is injected here -->
</thead>
<tbody>
<!-- Data is injected here -->
</tbody>
</table>

Calculate sum of merged rows and display in third column

I am trying to calculate the monthly expenses from my table.
Want to sum up all the amount month wise and display in total like for January month total will be $180, March will be $230 and May $200. The amount should reflect in the total column. I have created this table using ng-repeat of angular framework (dynamic table)
JSFIDDLE
I have tried below code which will sum up all the individual cols having only numeric values. This code is not working for merged rows.
for (col = 1; col < ncol + 1; col++) {
console.log("column: " + col);
sum = 0;
$("tr").each(function(rowindex) {
$(this).find("td:nth-child(" + col + ")").each(function(rowindex) {
newval = $(this).find("input").val();
console.log(newval);
if (isNaN(newval)) {
$(this).html(sum);
} else {
sum += parseInt(newval);
}
});
});
}
});
Any help on this will be really helpful.
I would add a data-month attribute to the cell displaying the amount, it is not visible to users, but super helpful for you. Have a look at the solution below.
function getMonth(month) {
var monthCells = $("td[data-month='" + month + "']"); // get all TDs with a data month attribute
var sum = 0;
for(var i = 0; i < monthCells.length; i++){ // iterate over the tds
var amountCell = monthCells[i]; // get a td for given iteration
var amountCellText = $(amountCell).text(); // get the text content
sum += parseInt(amountCellText.replace(/\D/, "")); // in amoutnCellText replace anything that's not a digit into an empty string
}
return sum;
}
console.log(getMonth("march"))
table, th, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
<th>Total</th>
</tr>
<tr>
<td rowspan="2">January</td>
<td data-month="january">$100</td>
</tr>
<tr>
<td data-month="january">$80</td>
</tr>
<tr>
<td rowspan="2">March</td>
<td data-month="march">$200</td>
</tr>
<tr>
<td data-month="march">$30</td>
</tr>
<tr>
<td>May</td>
<td data-month="may">$200</td>
</tr>
</table>
How about something like this?
vm.data = [
{
month: 'January',
savings: [
{ amount: 100 },
{ amount: 200}
]
},
{
month: 'February',
savings: [
{ amount: 300 },
{ amount: 400 }
]
}
];
In html:
<table class="table table-bordered table-condensed">
<tr>
<th>Month</th>
<th>Savings</th>
<th>Total</th>
</tr>
<tr ng-repeat="row in vm.data">
<td>{{row.month}}</td>
<td>
<table class="table table-bordered table-condensed">
<tr ng-repeat="s in row.savings">
<td>${{s.amount}}</td>
</tr>
</table>
</td>
<td>${{vm.getTotal(row.savings)}}</td>
</tr>
</table>
In JS:
vm.getTotal = getTotal;
function getTotal(savings) {
var total = 0;
angular.forEach(savings,
function (row) {
total += row.amount;
});
return total;
}
The key here is data modeling so that you have a simple function in getting total. Hope it will help.
Sample

Knockout.js - Sum table, add row and fill the table with AJAX

Im using this table to add materials and using Knockoutjs-3.4.0.js to add row and to sum it. My problem is when i try to edit the code i want to populate the table with a AJAX request. The problem is that i don't know how to fill the table with the AJAX response.
If i use the code below i get this error:
ReferenceError: Unable to process binding "click: function (){return
addMaterial }" Message: Can't find variable: addMaterial
<table class="table table-bordered">
<thead>
<tr>
<th>Moment</th>
<th>Antal </th>
<th>Kostnad</th>
<th>Totalt</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: materials">
<tr>
<td><input data-bind="value: name" /></td>
<td><input data-bind="value: quantity" /></td>
<td><input data-bind="value: rate" /></td>
<td data-bind="text: formattedTotal"></td>
<td></td>
</tr>
<tfoot>
<tr>
<th colspan="2"><button class="fa fa-plus btn-success" data-bind="click: addMaterial, enable: materials().length < 20"> Lägg till rad</button></th>
<th class="text-right">Totalt</th>
<th class="text-center"><span data-bind="text: totalSurcharge().toFixed(0)"></span></th>
<th> </th>
</tr>
<tr id="momsRow" class="hidden">
<th colspan="3" class="text-right">Moms</th>
<th class="text-center"><span data-bind="text: totalVat().toFixed(1)"></span></th>
<th> </th>
</tr>
<tr id="byggmomsRow" class="hidden">
<th colspan="3" class="">Omvänd byggmoms</th>
<th class="text-center"></th>
<th> </th>
</tr>
<tr>
<th colspan="3" class="text-right">Totalt:</th>
<th class="text-center"><span data-bind="text: totalPlusVat().toFixed(2)"></span></th>
<th> </th>
</tr>
</tfoot>
</tbody>
</table>
The knockout.js code:
/*------------- Load rows ------------- */
function LoadRows() {
var self = this;
self.materials = ko.observableArray([]);
$.getJSON("/json/tender_offer_edit_moment_json.asp", function(data) {
self.materials(data);
})
}
//ko.applyBindings(new dealModel());
ko.applyBindings(new LoadRows());
/*------------- Sum table ------------- */
function addMaterial() {
this.name = ko.observable("");
this.quantity = ko.observable("");
this.rate = ko.observable(0);
this.formattedTotal = ko.computed(function() {
return this.rate() * this.quantity();
}, this);
}
function documentViewModel(){
var self = this;
//create a materials array
self.materials = ko.observableArray([
new addMaterial()
]);
// Computed data
self.totalSurcharge = ko.computed(function() {
var total = 0;
for (var i = 0; i < self.materials().length; i++)
total += self.materials()[i].formattedTotal();
return total;
});
// add VAT(moms 25%) data
self.totalVat = ko.computed(function() {
var totalWithVat = 0;
for (var i = 0; i < self.materials().length; i++)
totalWithVat += self.materials()[i].formattedTotal();
totalWithVat = totalWithVat*0.25;
return totalWithVat;
});
// Totalt with VAT(moms 25%) data
self.totalPlusVat = ko.computed(function() {
var totalWithVat = 0;
for (var i = 0; i < self.materials().length; i++)
totalWithVat += self.materials()[i].formattedTotal();
totalWithVat = totalWithVat*1.25;
return totalWithVat;
});
// Operations
self.addMaterial = function() {
self.materials.push(new addMaterial());
}
self.removeMaterial = function(material) { self.materials.remove(material) }
}
ko.applyBindings(new documentViewModel());
/*------------- Sum table END ------------- */
There is a correct json format on the AJAX request.
[{"name":"Moment 1","quantity":"1","rate":"10","formattedTotal":"10"},{"name":"Moment 2","quantity":"2","rate":"20","formattedTotal":"40"}]
$.ajax({
url: "/json/tender_offer_edit_moment_json.asp",
type: "GET",
dataType: "json",
success: function (data) {
console.log(data);
alert(data);
//new addMaterial(data);
new addMaterial(data);
}
});
JsFiddle
First of all, you call ko.applyBindings() twice and to whole page,
it is not suitable in your situation:
To load the initial data you can do smth like this:
var vm = new documentViewModel();
$.getJSON("/json/tender_offer_edit_moment_json.asp", function(data) {
vm.materials(data);
})
ko.applyBindings(vm);
and delete this lines:
function LoadRows() {
var self = this;
self.materials = ko.observableArray([]);
$.getJSON("/json/tender_offer_edit_moment_json.asp", function(data) {
self.materials(data);
})
}
//ko.applyBindings(new dealModel());
ko.applyBindings(new LoadRows());

jquery .each loop odd behaviour

Hi I have the following code
html
<table id="tbPermission">
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
<tr>
<td>2</td>
<td>Test2</td>
</tr>
<tr>
<td>3</td>
<td>Test3</td>
</tr>
</table>
script
var trArray = [];
var tdArray = [];
var reruiredObj = {"UserID":null,
"UserName":null
};
var first;
var second;
$('#tbPermission tr').each(function () {
$(this).find('td').each(function (index) {
//alert(index+'-'+ $(this).html());
//alert(index);
if(index == 0){
first = $(this).html();
}
else{
second = $(this).html();
}
//alert(JSON.stringify(reruiredObj));
});
alert(first+'-'+second)
reruiredObj['UserID'] = first;
reruiredObj['UserName'] = second;
trArray.push(reruiredObj);
});
alert(JSON.stringify(trArray));
Demo Here
My question why first and second in undefined in first alert, and why it is
[{"UserID":"3","UserName":"Test3"},{"UserID":"3","UserName":"Test3"},{"UserID":"3","UserName":"Test3"},{"UserID":"3","UserName":"Test3"}]
my desired output is
[{"UserID":"1","UserName":"Test1"},{"UserID":"2","UserName":"Test2"},{"UserID":"3","UserName":"Test3"}]
The scope of your reruiredObj object is incorrect which is why you get the same object three times. Try this instead:
var trArray = [];
var tdArray = [];
var first;
var second;
$('#tbPermission tr:gt(0)').each(function () {
var reruiredObj = {
"UserID": null,
"UserName": null
};
first = $(this).find('td').eq(0).html();
second = $(this).find('td').eq(1).html();
reruiredObj['UserID'] = first;
reruiredObj['UserName'] = second;
trArray.push(reruiredObj);
});
console.log(JSON.stringify(trArray));
jsFiddle example
And the undefined values come from iterating over the first row which you don't want, and can ignore with tr:gt(0)
The first alert gives undefined because the first row of the table does not contain any td element.
To exclude the first row from the loop:
$('#tbPermission tr').each(function (i) {
if (i != 0) {
// execute ..
}
});
As for the array, try this in each loop:
var reruiredObj = { "UserID": first , "UserName":second };
Check the DEMO
Below works fine for me.
Since your first tr doesnt have td it gives undefined error. Try below one
<table id="tbPermission">
<thead>
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
<tr>
<td>2</td>
<td>Test2</td>
</tr>
<tr>
<td>3</td>
<td>Test3</td>
</tr>
</tbody>
</table>
<script>
$(function () {
var trArray = [];
var tdArray = [];
var reruiredObj = {"UserID":null,
"UserName":null
};
jsonObj = [];
var first;
var second;
$('#tbPermission tbody tr').each(function () {
$(this).find('td').each(function (index) {
//alert(index+'-'+ $(this).html());
//alert(index);
if(index == 0){
first = $(this).html();
}
else{
second = $(this).html();
}
//alert(JSON.stringify(reruiredObj));
});
alert(first+'-'+second)
item = {}
item ["UserID"] = first;
item ["UserName"] = second;
jsonObj.push(item);
});
console.log(jsonObj);
});
</script>
alert jsonObj. This gives the required result.

Categories

Resources