How to create array of object from HTML Table in javascript? - javascript

How can I create an array of objects from an HTML table body? This is how my HTML looks like
<tbody id="metadata">
<tr>
<td><input type="numeric" /></td>
<td><input type="numeric" /></td>
</tr>
<tr>
<td><input type="numeric" /></td>
<td><input type="numeric" /></td>
</tr>
<tr>
<td><input type="numeric" /></td>
<td><input type="numeric" /></td>
</tr>
</tbody>
here is what I tried this javascript to get all the values from the table cell in an array of objects. I don't understand why my cMetadata always return a blank array
let cMetadata;
if (document.querySelectorAll("metadata")) {
let tableData = document.querySelectorAll("metadata");
cMetadata = [...tableData].map((row) => {
return {
altions: row.cells[0].textContent,
lexity: row.cells[1].textContent,
};
});
}
final array of object should look like
cMetadata = [{altions: 1 , lexity: 2},{altions: 2 , lexity: 2},{altions: 3 , lexity: 2}]

Verified that you have the tbody node inside a table node. You can get the items with document.querySelectorAll("#metadata tr"):
const btn = document.querySelector("button");
btn.addEventListener("click", () => {
const elements = document.querySelectorAll("#metadata tr");
const result = Array.from(elements).map(tr => {
const childs = tr.querySelectorAll("input");
return {
p1: childs[0].value,
p2: childs[1].value
};
});
console.log(result);
});
<table>
<tbody id="metadata">
<tr>
<td><input type="numeric"></td>
<td><input type="numeric"></td>
</tr>
<tr>
<td><input type="numeric"></td>
<td><input type="numeric"></td>
</tr>
<tr>
<td><input type="numeric"></td>
<td><input type="numeric"></td>
</tr>
</tbody>
</table>
<button>Get Data</button>

Related

serialize inputs inside element (not form)

I have a HTML like:
<table>
<tr id="01">
<td><input name="x"></td>
<td><input name="y"></td>
</tr>
<tr id="02">
<td><input name="x"></td>
<td><input name="y"></td>
</tr>
</table>
And I'm trying to make a JSON string of the inputs only on a specific row. Would there be a good solution for this? Something like:
json = $('#01').serialize();
but I need a json instead of the URLEncode'd string the serialize() provides.
serialize() won't give you the JSON you're after. It'll only give you a URLEncode'd string. Example:
//test all inputs on row #02
window.tester = function() {
console.log($('#02 input').serialize());
};
//test all inputs
window.tester2 = function() {
console.log($('input').serialize());
};
//test only "y" inputs
window.tester3 = function() {
console.log($("input[name='y']").serialize());
};
<table>
<tr id="01">
<td><input name="x" value="1"></td>
<td><input name="y" value="2"></td>
</tr>
<tr id="02">
<td><input name="x" value="3"></td>
<td><input name="y" value="4"></td>
</tr>
</table>
<div>
<input type="button" onclick="tester()" value="Test Row 02" /><br />
<input type="button" onclick="tester2()" value="Test All Inputs" /><br />
<input type="button" onclick="tester3()" value="Test Only 'y' Inputs" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Produces:
x=3&y=4
x=1&y=2&x=3&y=4
y=2&y=4
If it's JSON you want, then you'll need to be specific about what format you're after. An array? A hash? In any case, the selectors above are what you'll want to start with, then at some point, you'll want to run the value through:
JSON.stringify(myResults);
window.arrayIt = function () {
var arrVal = $('#02 input').toArray();
var arr = arrVal.map(function (i) {
var x = {};
x[i.name] = i.value;
return x;
});
console.log(JSON.stringify(arr));
}
<table>
<tr id="01">
<td><input name="x" value="1"></td>
<td><input name="y" value="2"></td>
</tr>
<tr id="02">
<td><input name="x" value="3"></td>
<td><input name="y" value="4"></td>
</tr>
</table>
<button onclick="arrayIt()">Array It!</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
.serialize() can be used on a collection of inputs.
$("#submit").click(function() {
var data = $("#01 input").serialize();
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="01">
<td><input name="x"></td>
<td><input name="y"></td>
</tr>
<tr id="02">
<td><input name="x"></td>
<td><input name="y"></td>
</tr>
</table>
<button id="submit">Click</button>
BTW, the result of serialize() isn't JSON, it's application/x-www-form-urlencoded format.
You can use $("#01 input").serialize().
$('#abc').click(function(){
json = $("#01 input").serialize().replace(/%20/g, "+");
console.log(json);
});
<table>
<tr id="01">
<td><input name="x"></td>
<td><input name="y"></td>
</tr>
<tr id="02">
<td><input name="x"></td>
<td><input name="y"></td>
</tr>
</table>
<button id = "abc">serialize 01</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Sum total of all text box value in a row using jquery

I want to sum all the text box value in a html table row using jQuery.
here is the table:
<table border="1">
<tr>
<th>sl</th>
<th>TA</th>
<th>DA</th>
<th>HA</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input id="expenses_sum"></td>
</tr>
<tr>
<td>2</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input id="expenses_sum"></td>
</tr>
<tr>
<td>3</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input id="expenses_sum"></td>
</tr>
</table>
Here is the jQuery function to add the value of all text box of class expenses and display the result in a text box of id expenses_sum.
$(document).ready(function() {
$(".expenses").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
$(".expenses").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#expenses_sum").val(sum.toFixed(2));
}
how to use this function for each row.
Firstly you have repeated the same id when they should be unique which means your HTML is invalid. You should use a common class instead.
To make this work you need to restrict the .expenses selector to only find the elements within the same row as the input which was changed. To do that you can use closest() to get the nearest parent tr, then find() to get all the inputs.
Also note there are several logic improvements you can make here:
remove the each() loop to add the event handler
providing the reference of calculateSum to the event handler so you can use the this keyword to traverse the DOM
provide a default value of 0 to the value to simplify the sum logic
hook to the change event as well as keyup for when users paste data in to the field. Try this:
$(document).ready(function() {
$(".expenses").on('keyup change', calculateSum);
});
function calculateSum() {
var $input = $(this);
var $row = $input.closest('tr');
var sum = 0;
$row.find(".expenses").each(function() {
sum += parseFloat(this.value) || 0;
});
$row.find(".expenses_sum").val(sum.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<th>sl</th>
<th>TA</th>
<th>DA</th>
<th>HA</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses_sum"></td>
</tr>
<tr>
<td>2</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses_sum"></td>
</tr>
<tr>
<td>3</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses_sum"></td>
</tr>
</table>
you can use like this
$(document).on('keyup change','input.expenses',function(){
$expenses = $(this).parents('tr').find('.expenses');
$expenseTotal = $(this).parents('tr').find('#expenses_sum');
$expenseTotal.val('0');
$.each($expenses,function(index,object){
if($(object).val()!='')
{
$expenseTotal.val(parseInt($expenseTotal.val())+parseInt($(object).val()));
}
});
});
see demo at - https://jsfiddle.net/Vesharj/zLg3pyq4/
Here is the right way to do this.
<table border="1">
<tr>
<th>sl</th>
<th>TA</th>
<th>DA</th>
<th>HA</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input class="expenses_sum"></td>
</tr>
<tr>
<td>2</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input class="expenses_sum"></td>
</tr>
<tr>
<td>3</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input class="expenses_sum"></td>
</tr>
</table>
And js :
$(document).ready(function(){
$(".expenses").each(function() {
$(this).keyup(function(){
sum($(this).parents("tr"));
});
});
});
function sum(parent){
var sum = 0;
$(parent).find(".expenses").each(function(){
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$(parent).find(".expenses_sum").val(sum.toFixed(2));
}
Hope, it helps

convert html table with various kind of condition to Json

I am stuck to generate the JSON based on the HTML below
<table>
<thead>
<tr>
<th>Date</th>
<th>Rainfall <small>(Milimeter)</small></th>
<th>Reservoir Level <small>(Meter)</small></th>
<th>T/Water <small>(Meter)</small></th>
<th>W/Supply <small>(Cumec)</small></th>
<th>C/Station <small>(Cumec)</small></th>
<th>Remarks </th>
<th>Task</th>
</tr>
</thead>
<tbody>
<tr>
<td>01/06/2014</td>
<td>120</td>
<td>120</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><span class="glyphicon glyphicon-ok"></span></td>
</tr>
<tr>
<td>02/06/2014</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><span class="glyphicon glyphicon-ok"></span></td>
</tr>
<tr>
<td>03/06/2014</td>
<td><input type="text" id="44"></td>
<td><input type="text" id="45"></td>
<td><input type="text" id="46"></td>
<td><input type="text" id="47"></td>
<td><input type="text" id="48"></td>
<td><input type="text" id="49"></td>
<td><button class="btn btn-info btn-xs Save">Save</button></td>
</tr>
<tr>
<td>04/06/2014</td>
<td><input type="text" id="44"></td>
<td><input type="text" id="45"></td>
<td><input type="text" id="46"></td>
<td><input type="text" id="47"></td>
<td><input type="text" id="48"></td>
<td><input type="text" id="49"></td>
<td><button class="btn btn-info btn-xs Save">Save</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="9"></td>
</tr>
</tfoot>
</table>
As you can see, some cell are blanks, some are mixed with <small>, <span>, and <input>. What I failed to achieve is how to produce the json out of this table in the following format
["Date", "Rainfall (milimeter)", "Reservoir Level (meter)","T/Water (meter)","W/Supply (cumec)","C/Station (cumec)","Remarks","Task"],
["01/06/2014", "120", "120","","","","","OK"],["02/06/2014", "120", "120","","","","","OK"],["03/06/2014", "12", "100","","","","","X"]
From the above format, you can see all values in cell are captured. As for <input> element, I need to pull value of it and append it to json result. Below is what I have right now. So far no luck
buildTableBody = function() {
var data = [],
table = $('table', el)[0];
for (var i=0; i<table.rows.length; i++) {
var tableRow = table.rows[i],
rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
var rc = tableRow.cells[j].innerHTML.toLowerCase().replace(/ /gi,'');
if ((rc) || (!_(rc).isBlank())) {
//console.log(rc);
var cl = _(_(rc).stripTags()).humanize();
if (cl == 'task') {
rowData[i] = 'Status';
} else if (cl == 'Save') {
rowData[i] = 'X'
}
} else {
rowData[i] = ' ';
}
}
data.push(rowData[i]);
}
//console.log(data);
return data;
}
Thank you

How to add two textbox value and show in other textbox for all rows

I have create table in html.It will show like excel sheet.I want to multiply dealer price and Quantity textbox value which show in Total Price. It is applicable for all row.
My code is .....
<table id="my-table">
<tr>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td><input class="price" type="text"></td>
<td><input class="quantity" type="text"></td>
<td><input class="total" type="text"></td>
</tr>
<tr>
<td><input class="price" type="text"></td>
<td><input class="quantity" type="text"></td>
<td><input class="total" type="text"></td>
</tr>
</table>
How can i do it....
I suppose that you have a table structure like this:
<table id="my-table">
<tr>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td><input class="price" type="text"></td>
<td><input class="quantity" type="text"></td>
<td><input class="total" type="text"></td>
</tr>
<tr>
<td><input class="price" type="text"></td>
<td><input class="quantity" type="text"></td>
<td><input class="total" type="text"></td>
</tr>
</table>
After document ready, register onchange event on price and quantity element in whole table
$(document).ready(function() {
$('#my-table').on('change', '.price', calTotal)
.on('change', '.quantity', calTotal);
// find the value and calculate it
function calTotal() {
var $row = $(this).closest('tr'),
price = $row.find('.price').val(),
quantity = $row.find('.quantity').val(),
total = price * quantity;
// change the value in total
$row.find('.total').val(total)
}
});
Demo here
else if u use mysql query means its so simple
try to add both in query itself and it ll applicable for all rows
else you can use quantity blur event

Copy table row and increment all name attributes

Let's have a table like this:
<table>
<tr>
<td><input type="text" name="FirstName1" /></td>
<td><input type="text" name="LastName1" /></td>
</tr>
<tr>
<td><input type="text" name="FirstName2" /></td>
<td><input type="text" name="LastName2" /></td>
</tr>
</table>
I want to have a button that will add new row at the end of the table with incremented name attributes so it will look like this:
<table>
<tr>
<td><input type="text" name="FirstName1" /></td>
<td><input type="text" name="LastName1" /></td>
</tr>
<tr>
<td><input type="text" name="FirstName2" /></td>
<td><input type="text" name="LastName2" /></td>
</tr>
<tr>
<td><input type="text" name="FirstName3" /></td>
<td><input type="text" name="LastName3" /></td>
</tr>
</table>
And so on.
So far I have this but it does not increment name attributes:
$("#newRowButton").click(function(){
$("table tr:last").clone().appendTo("table");
});
$("#newRowButton").click(function() {
$("table tr:last")
.clone()
.appendTo("table")
.find(':input')
.attr('name', function(index, name) {
return name.replace(/(\d+)$/, function(fullMatch, n) {
return Number(n) + 1;
});
})
});
Live demo.
$("#newRowButton").click(function(){
var trows = $("table tr:last").clone();
trows.find('td input').attr("name",function(i,a){
var p = new RegExp("((?:[a-z][a-z]+))(\\d+)",["i"]);
var m = p.exec(a);
var index = parseInt(m[1]);
index++;
return m[0]+index;
});
trows.appendTo("table");
});
var clonedRow = $("#EventType tr:last").clone();
$("input", clonedRow).attr('name', 'FirstName3'); // reset the name
you can get the name attribute and increment by 1
Reference

Categories