multiple array table in javascript - javascript

**Currently I have written code for calculating sum of input on my input
for One Table**
$('#example122').on('input', '.calculate', function () {
calculateTotal();
});
function calculateTotal()
{
var grandTotal = 0;
$('#example122 tbody tr').each(function() {
var c_sbt = $('.calculate', this).val();
grandTotal += parseFloat(c_sbt);
});
// VAT, DISCOUNT, SHIPPING, TOTAL, SUBTOTAL:
var subT = parseFloat(grandTotal);
$('.sub_total').val(subT.toFixed(2));
}
**But now i want code for multiple table having same ID **
$('table').foreach(on('input', '.calculate', function () {
calculateTotal();
}));
function calculateTotal()
{
var grandTotal = 0;
$('table tbody tr').each(function() {
var c_sbt = $('.calculate', this).val();
grandTotal += parseFloat(c_sbt);
});
// VAT, DISCOUNT, SHIPPING, TOTAL, SUBTOTAL:
var subT = parseFloat(grandTotal);
$('.sub_total').val(subT.toFixed(2));
}
** this code is not working **
HTML CODE
my table data is a input type="text" i want to calculate when user changes the value
<td style="padding-top:15px;" align="right"><b>TOTAL SALARY</b>
</td>
<td>
<input type="text" style="text-align:right;" name="sub_total" id="sub_total" class="form-control sub_total" autocomplete="off" class="form-group" ></td>
</tfoot>

It's hard to know when you don't have the HTML in your post but I think that your main issue is that you're using the keyword foreach when you try to iterate over your tables. As you can se when you iterate over your rows you use each.
Below is a snippet that does something in line with what it looks like you're after. That is, it iterates over multiple tables and adds the values for each column on each row in each table up.
This is probably not exactly what you're trying to do but might point you in the right direction.
$(document).ready(function() {
$('table').each(function() {
calculateTotal(this);
});
})
function calculateTotal(table) {
var grandTotal = parseFloat($('.sub_total').text());
$(table).find('tbody tr').each(function() {
var c_sbt = $(this).text();
grandTotal += parseFloat(c_sbt);
});
var subT = parseFloat(grandTotal);
$('.sub_total').html(subT.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="this">10.2</td>
</tr>
<tr>
<td class="this">12.3</td>
</tr>
</table>
<table>
<tr>
<td class="this">10.2</td>
</tr>
<tr>
<td class="this">10.22</td>
</tr>
</table>
<p class="sub_total">0</p>

Related

refreshing javascript calculated sum total on new checkbox use without input fields

With help I've gotten this script to change the class of the function to include countable but need to get the total calculation to update the sum of all fields shown when that change takes place.
The scripts are split with the top one set to calculate the total of all countable class fields and the second script section set to show the line items and add the countable class.
<script>
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.countable').each(function(i){
totals[i]+=parseInt( $(this).html());
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html("total:"+totals[i]);
});
});
</script>
<script>
$(document).ready(function() {
$("input[type=checkbox]").change(function() {
var val = $(this).val();
var isChecked = $(this).is(":checked");
var $trElement = $('.' + val);
var $tdPriceElement = $trElement.find('td.price');
$trElement.toggle(isChecked);
$tdPriceElement.toggleClass('countable', isChecked);
});
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
These checkboxes allow display of the line items when selected.
<input class="my-activity" type="checkbox" value="42"/> example<br/>
<input class="my-activity" type="checkbox" value="43"/> example<br/>
<table id="sum_table">
<tr class="42" style="display:none">
<td>example</td>
<td></td>
<td></td>
<td class="price">7800</td>
</tr>
<tr class="43" style="display:none">
<td>First Area</td>
<td></td>
<td></td>
<td class="price">6900</td>
</tr>
<tr class="totalColumn">
<td>Total:</td>
<td></td>
<td class="totalCol"></td>
</tr>
</table>
You need to load jQuery before you can use it, so move:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
above the other 2 scripts. Then, replace your first script with this:
function showTotal(){
//grab the .countable elements from the #sum_table
var $countables =$("#sum_table .countable");
//loop through and add up the total from their texts
var total = 0;
for(var i = 0; i < $countables.length; i++){
total += Number($countables.eq(i).text());
}
//put the total in the .totalCol element
$("#sum_table td.totalCol").html(total);
}
and call this function at the end of your onchange function, like this:
$(document).ready(function() {
$("input[type=checkbox]").change(function() {
var val = $(this).val();
var isChecked = $(this).is(":checked");
var $trElement = $('.' + val);
var $tdPriceElement = $trElement.find('td.price');
$trElement.toggle(isChecked);
$tdPriceElement.toggleClass('countable', isChecked);
//CALL IT HERE:
showTotal();
});
});

td background colouring applied to complete column rather to a single cell

I've below html.
<table border="1" class="myTable">
<tr>
<th class="cname">Component</th>
<th class="pname">Properties</th>
<th class="sname">lqwasb02</th>
</tr>
<tr>
<td class="cname">EMWBISConfig</td>
<td class="pname">reEvaluationTimer</td>
<td class="pvalue">every 1 hour without catch up</td>
</tr>
<tr>
<td class="cname">CalculateCategoryMediaInfoService</td>
<td class="pname">scheduled</td>
<td class="pvalue">yes</td>
</tr>
<tr>
<td class="cname">EMWBISScheduler</td>
<td class="pname">scheduled</td>
<td class="pvalue">no</td>
</tr>
<tr>
<td class="cname">CatalogTools</td>
<td class="pname">loggingDebug</td>
<td class="pvalue">false</td>
</tr>
</table>
Below is the jquery I've written.
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
$.each(list,function(index,value){
//alert(index+' : '+value);
});
var idx;var list2 = new Array();
// Find index of cell with 'lqwasb02'
$('.myTable th').each(function(index) {
if ($(this).text() === 'lqwasb02') idx = index;
});
// Loop through each cell with the same index
$('.myTable tr').each(function() {
if($(this).find('td:eq('+idx+')').text() !=""){
list2.push($(this).find('td:eq('+idx+')').text());
}
}); var idx2 = [];
for(var x=0;x<list2.length;x++){
if(list[x]===list2[x]){
//console.log(list[x]);
}else{
console.log('mismatched : '+list[x]);
$('.myTable tr').each(function() {
$(this).find('td:eq('+x+')').css("background-color", "red");
});
idx2.push(x);
}
}
});
I'm trying to compare values in list with values in lqwasb02 column and if it finds the difference, it should highlight the background of td cell in red colour.
Current issue with jquery code, it is highlighting the complete column.
Can someone please help me where I'm getting wrong? If possible, please pass on the recommended solutions.
Many Thanks in advance.
The problem is that in your .find you are returning multiple elements that it's selector matches. So as opposed to storing the text value for your td elements in the second array, just store the actual td element, compare it's text, and then you can assign the background color directly to the element as opposed to finding it again via it's index:
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
$.each(list,function(index,value){
//alert(index+' : '+value);
});
var idx;var list2 = new Array();
// Find index of cell with 'lqwasb02'
$('.myTable th').each(function(index) {
if ($(this).text() === 'lqwasb02') idx = index;
});
// Loop through each cell with the same index
$('.myTable tr').each(function() {
if($(this).find('td:eq('+idx+')').text() !=""){
list2.push($(this).find('td:eq('+idx+')')); // <-- Store the object here, not it's text value.
}
});
var idx2 = [];
for(var x=0; x < list2.length; x++){
if(list[x]===list2[x].text()) { // <-- compare list[x] to the text value of list2[x]
//console.log(list[x]);
} else {
list2[x].css("background-color", "red"); // <-- no find or selector needed, just apply it to the object you stored earlier.
};
idx2.push(x);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" class="myTable">
<tr>
<th class="cname">Component</th>
<th class="pname">Properties</th>
<th class="sname">lqwasb02</th>
</tr>
<tr>
<td class="cname">EMWBISConfig</td>
<td class="pname">reEvaluationTimer</td>
<td class="pvalue">every 1 hour without catch up</td>
</tr>
<tr>
<td class="cname">CalculateCategoryMediaInfoService</td>
<td class="pname">scheduled</td>
<td class="pvalue">yes</td>
</tr>
<tr>
<td class="cname">EMWBISScheduler</td>
<td class="pname">scheduled</td>
<td class="pvalue">no</td>
</tr>
<tr>
<td class="cname">CatalogTools</td>
<td class="pname">loggingDebug</td>
<td class="pvalue">false</td>
</tr>
</table>
$('.myTable tr').each(function() {
$(this).find('td:eq('+x+')').css("background-color", "red");
});
this piece of code assign a background colour to each cell of index 'x' for each rows (each cells of index x of each table rows represent a column).
You have to select only the rows which contains the cells you want to colour.
Here is how i would have approached solving this issue:
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
var colIndex = findColIndex('lqwasb02');
// Loop over table rows
$('tr').each(function(){
// Look up cell with specific index
var $cell = $(this).find('td').eq(colIndex);
// Check if the text of the cell is not present in the list and do smth
if ($.inArray($cell.text(), list) === -1) {
$cell.css('background', 'red')
}
});
});
// helper function to find the index of column by text in the header
function findColIndex (headerText) {
var $col = $('.myTable th:contains(' + headerText + ')');
return $('.myTable th').index($col);
}
https://jsbin.com/fafegi/1/edit?js,output

How to get the values from dynamically created row of textboxes in JSON

I am trying to create a row of text boxes dynamically through Javascript and read the values of the textbox in JSON. Later,I have to read JSON and display the values in textarea and this should achieved only though jquery and javascript.
I am able to create the text boxes dynamically but I am unable to read the values in JSON. When I use the jQuery part(mentioned below),the javascript to dynamically create textboxes is not working.Any suggestions please.
<table id="myTable">
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Occupation and Employer</th>
<th>Add</th>
<tr>
<td><input type="text" id="txtName" /></td>
<td><input type="text" id="txtAge" /></td>
<td><input type="text" id="txtGender" /></td>
<td><input type="text" id="txtOccupation" /></td>
<td><input type="button" id="btnAdd" class="button-add" onClick="insertRow()" value="add"></input></td>
<td><input type="button" id="btnSave" class="button-add" value="Save"></input> </td>
</tr>
</table>
<script>
var index = 1;
function insertRow()
{
var table=document.getElementById("myTable");
var row=table.insertRow(table.rows.length);
var cell1=row.insertCell(0);
var t1=document.createElement("input");
t1.id = "txtName"+index;
cell1.appendChild(t1);
var cell2=row.insertCell(1);
var t2=document.createElement("input");
t2.id = "txtAge"+index;
cell2.appendChild(t2);
var cell3=row.insertCell(2);
var t3=document.createElement("input");
t3.id = "txtGender"+index;
cell3.appendChild(t3);
var cell4=row.insertCell(3);
var t4=document.createElement("input");
t4.id = "txtOccupation"+index;
cell4.appendChild(t4);
index++;
}
$(document).ready(function(){
$("#btnsave").click(function ()
{
alert("Hi");
var dataToSend={
'Name':[],
'Age':[]};
dataToSend.Name.push({$("txtName").val().trim()});
dataToSend.Age.push({$("txtAge").val().trim()});
localStorage.setItem('DataToSend', JSON.stringify(DataToSend));
var restoredSession = JSON.parse(localStorage.getItem('dataToSend'));
// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);
alert(restoredSession);
});
});
JSFIddle:http://jsfiddle.net/S7c88/
Since you are using jQuery you can greatly simplify the whole process by using methods like clone().
Here's a working example where I created one array of row objects. Since you aren't doing this in a form, I removed the ID's and just used data-name.
var $row;
function insertRow() {
$('#myTable').append($row.clone());
}
$(function () {
$row = $('tr').eq(1).clone(); /* clone first row for re-use*/
$('#myTable').on('click', '.btnSave', function () {
var dataToSend = [];
$('tr:gt(0)').each(function () {
var data = {};
$(this).find('input').each(function () {
data[$(this).data('name')] = this.value
});
dataToSend.push(data);
});
/* display data in textarea*/
$('#output').val(JSON.stringify(dataToSend, null, '\t'))
});
}) ;
I changed your input type=button to button to take advantage of using input selector while looping rows to create data and not have to filter out the buttons
Your demo has invalid html, missing <tr> for top set of <th>
DEMO
Some areas where you were going wrong:
$("txtName") Invalid selector
No row references in attempt to gather data

How to get <td> value in textbox

I've done some code in html and in JavaScript ... My query is when I click on <td>, whatever the value associated with it, has to be displayed in the corresponding text box ...
In front of <td> I've taken the textbox ... for an example I've taken 3 <td> and 3 textboxes
<script type="text/javascript">
function click3(x) {
x = document.getElementById("name").innerHTML
var a = document.getElementById("txt");
a.value = x;
}
function click1(y) {
y = document.getElementById("addr").innerHTML
var b = document.getElementById("txt1");
b.value = y;
}
function click2(z) {
z = document.getElementById("email").innerHTML
var c = document.getElementById("txt2");
c.value = z;
}
</script>
this is my JavaScript code , I know this is not an adequate way to deal such problem, since its giving static way to deal with this problem
does anyone have a better solution for this problem ??
In JavaScript/jQuery
If click1, click2 and click3 are supposed to be three event then you have to keep all three function you can shorted the script code for assigning values to text field.
<script type="text/javascript">
function click3(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
}
function click1(y) {
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
}
function click2(z) {
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
</script>
You can make a single function if you have single click event and shorten the code for assignment like this,
function SomeClick(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
As far as I understood your question, you could try the following, assuming that's how your HTML is structured:
HTML Markup:
<table id="mytable">
<tr>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
<tr>
<td class="name">Tom</td>
<td class="addr">789</td>
<td class="email">tom#dot.com</td>
</tr>
<tr>
<td class="name">Dick</td>
<td class="addr">456</td>
<td class="email">dick#dot.com</td>
</tr>
<tr>
<td class="name">Harry</td>
<td class="addr">123</td>
<td class="email">harry#dot.com</td>
</tr>
</table>
<input id="txt1" type="text" />
<input id="txt2" type="text" />
<input id="txt3" type="text" />​
jQuery:
$(".name").click(function(){
$("#txt1").val($(this).text());
$("#txt2").val($(this).nextAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(1).text());
});​
$(".addr").click(function(){
$("#txt2").val($(this).text());
$("#txt1").val($(this).prevAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(0).text());
});
$(".email").click(function(){
$("#txt3").val($(this).text());
$("#txt2").val($(this).prevAll().eq(0).text());
$("#txt1").val($(this).prevAll().eq(1).text());
});
DEMO: http://jsfiddle.net/Z9weS/
You can combine columns and rows. Per cell consisting id you give it th column title and
number of series it could be the index of the row combination of row and column gives the
address as per table cell by a specific event you can read the value of the id
Then you know to pull the cell value.
$('tr')
.click(function() {
ROW = $(this)
.attr('id');
$('#display_Colume_Raw')
.html(COLUME + ROW);
$('#input' + COLUME + ROW)
.show();
STATUS = $("#input" + COLUME + ROW)
.val();
});

How to delete a table row on button click of corresponding row?

This is my code:
function deleteHostTable(src) {
var table = src.parentNode.parentNode.parentNode;
if(table.rows.length > 1) {
table.deleteRow(src.parentNode.parentNode);
}
}
function addHost(src) {
var table = src.parentNode.parentNode.parentNode;
var newRow = table.insertRow(table.rows.length-1);
var cell = newRow.insertCell(newRow.cells.length);
cell.innerHTML = '<input type="hidden" name = "vtierIdH" value = "vtierId" />'
cell = newRow.insertCell(newRow.cells.length);
cell.innerHTML = '<img src="images/minus.gif" onclick="deleteHostTable(this);return false;"/>';
cell = newRow.insertCell(newRow.cells.length);
cell.className = "pagetitle";
cell.innerHTML = '<input type = "text" value="hstst" />';
}
</script>
<html>
<table id="host#1" index="1">
<tr>
<td colspan="10">
<h2 align="left" class="pagetitle">Sub Account Hosts:</h2>
</td>
</tr>
<tr>
<input type="hidden" name="vtierIdH" value="<%=vtierId %>" />
<td><button id="minus" onclick="deleteHostTable(this);"/></td>
<td class="pagetitle"><input type="text" value="hstst" /></td>
</tr>
<tr>
<td><button onclick="addHost(this);"></td>
</tr>
</table>
</html>
Now, when i click the button corresponding to a button, this code deletes the uppermost row
and not the row corresponding to that button which is clicked. How can i delete the row corresponding to the button in that row?
Just change your remove function to
function deleteHostTable(src) {
var row = src.parentNode.parentNode;
row.parentNode.removeChild(row);
}
The reason it's not working with deleteRow is that it expects the index of the row to be passed while you are passing an object.
You must pass "index" to the table.deleteRow function, not the element.
function deleteHostTable(src) {
var table = src.parentNode.parentNode.parentNode;
var row = src.parentNode.parentNode;
for(var i = table.rows.length; i--; )
{
if ( table.rows[i] == row )
{
table.deleteRow(i);
return;
}
}
}
this function should work.
You also can use src.parentNode.parentNode.parentNode.removeChild(src.parentNode.parentNode)

Categories

Resources