I need to sum some text elements and update an input text, following is the far I could go:
This would be a correct example. I want to sum the text from within the <span> if the the <tr> contains the class ui-state-error
HTML
<table>
<tr id="rp-10-1-1" class="ui-state-error" style="width:50px; height:50px;">
<td><span id="pr-10-1-1">100</span><td>
</tr>
<tr id="rp-10-1-2" class="ui-state-highlight" style="width:50px; height:50px;">
<td><span id="pr-10-1-2">200</span><td>
</tr>
<tr id="rp-10-1-3" class="ui-state-error" style="width:50px; height:50px;">
<td><span id="pr-10-1-3">300</span><td>
</tr>
</tr>
</table>
<input type="text" id="sumhere">
JAVASCRIPT
$( 'tr[id^="rp-"]' ).click(
function() {
$('tr[id^="rp-"]').each(function(data, val) {
var rps = $(this).attr("id").split("-");
if ($("#pr-" + rps[1] + '-' + rps[2] + '-' + rps[3]).hasClass("ui-state-error")) {
console.log($("#pr-" + rps[1] + "-" + rps[2] + "-" + rps[3]).text());
}
});
}
);
tr would td are not recognized as a valid html. If you wish to extract just the total of the span elements, you may do the following :
var total = 0;
$('span[id^=hp]').each(function() // selects span starting with id=hp
{
total += parseInt($(this).text());
});
$("#sumhere").val(total);
Based on your updated HTML :
var total = 0;
$('tr[id^=rp-10-1] span').each(function() // selects span withing the tr element starting with id=rp-10-1
{
if(!isNaN(parseInt($(this).text()))) // condition for safety check while converting text to interger.
total += parseInt($(this).text());
});
$("#sumhere").val(total);
Example : https://jsfiddle.net/DinoMyte/7nhx26a2/3/
Demo: https://jsfiddle.net/zzaj1jye/
HTML:
<tr id="rp-10-1-1">
<span id="hp-10-1-1" class="ui-state-error">10</span>
<span id="hp-10-1-2" class="ui-state-error">20</span>
<span id="hp-10-1-3" class="ui-state-error">30</span>
</tr>
<input type="text" id="sumhere">
JS:
$(function() {
var total = 0;
$('span').each(function() {
if ( $(this).hasClass('ui-state-error') ) {
total += parseInt($(this).text());
}
});
$("#sumhere").val(total);
});
Related
I am trying to get value of subtotal field in my table, currently i am using table ID in .each function but my table ID increments dynamically on each section added, that is why i am not able to get value of subtotal and add each subtotal to get grand total.
This function is adding sub_totals to get grand subtotal
function calculateTableSum(currentTable) {
var sum = 0;
$('#' + currentTable + ' input.sub_total').each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$('#' + currentTable + ' input.sumamtcollected').val(sum.toFixed(2));
This is where is want to use table class instead of table ID
$('#' + currentTable + ' input.sumamtcollected').each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
grand += parseFloat(this.value);
alert(this.value);
}
This is my table
<table id="addaccount'+counter+'" class="table table-bordered"><tbody> <tr class="invoice-total" bgcolor="#f1f1f1"><td colspan="3" align="right"><strong>Sub-Total</strong></td><td><i class="fa fa-inr"></i><input class="sumamtcollected form-control " name="accttotal[]" type="text" value="" readonly style="background-color:white" ></td><td></td></tr></body></table>
Where currentTable is
var currentTable = $(this).closest('table').attr('id');
Alternatively, you may modify your selector to query all table's that have an id that start with 'addaccount' like so:
$('table[id^="addaccount"]')
$('table[id^="addaccount"]').each(function() {
console.log(this);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="addaccount1" class="table table-bordered">
<tbody>
<tr class="invoice-total" bgcolor="#f1f1f1">
<td colspan="3" align="right"><strong>Sub-Total</strong></td>
<td><i class="fa fa-inr"></i><input class="sumamtcollected form-control " name="accttotal[]" type="text" value="" readonly style="background-color:white"></td>
<td></td>
</tr>
</body>
</table>
<table id="addaccount2" class="table table-bordered">
<tbody>
<tr class="invoice-total" bgcolor="#f1f1f1">
<td colspan="3" align="right"><strong>Sub-Total</strong></td>
<td><i class="fa fa-inr"></i><input class="sumamtcollected form-control " name="accttotal[]" type="text" value="" readonly style="background-color:white"></td>
<td></td>
</tr>
</body>
</table>
In my table I have 2 rows please see my screen shot,suppose I click first check box means I want to take that id ** and **to_area value in jquery how can do this,I tried but I can not get please help some one
$(document).ready(function() {
$('#chemist_allotment_btn').click(function() {
if ($('#chemist_allotment_form').valid()) {
$.ajax({
url: 'update_chemist_bulk_transfer.php',
type: 'POST',
data: $('form#chemist_allotment_form').serialize(),
success: function(data) {
var res = jQuery.parseJSON(data); // convert the json
console.log(res);
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function(key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td>' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td>' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
$('#SampleDT tbody').empty().append(htmlString);
$('#get_to_area').click(function() {
var id = $('input[name=getchemist]:checked').val();
if ($(".getchemist").prop('checked') == true) {
alert(id);
alert(value.to_area);
} else {
alert('Please Check');
}
});
} else {
$('#SampleDT tbody').empty().append('No Datas Found');
}
},
});
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<center>
<div class="form-group">
<button type="button" class="btn btn-primary" style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
Firstly, add classes to each <td>, like <td class='id'>[Your id]</td>
Similarly for all the elements doctor-name, to-area, etc and a class to each <tr> like row-select
Somewhat like this:
<tr class="row-select">
<td class="select">...</td>
<td class="id">...</td>
<td class="to-area">...</td>
.
.
.
</tr>
Use jQuery like this:
$('.row-select').click(function(){
var id,toArea,checkBox;
id = $(this).find('.id').html(); //get the ID field
toArea = $(this).find('.to-area').html(); //get the to-area field
checkBox = $(this).find('.select > input');
checkbox.prop('checked',!checkbox.prop('checked'));
})
This code will get you he value no mater where you click on the row, and also invert the selection on the checkbox
To get the values of rows selected when the form is submitted run a loop like this
$('.row-select input:checked').each(function(){
var id,toArea,checkBox;
id = $(this).closest('tr').find('.id').html(); //get the ID field
toArea = $(this).closest('tr').find('.to-area').html(); //get the to-area field
})
EDIT
All together:
$(document).ready(function() {
$('#btnSubmit').click(function() {
$('.row-select input:checked').each(function() {
var id, name;
id = $(this).closest('tr').find('.id').html();
name = $(this).closest('tr').find('.name').html();
alert('ID: ' + id + " | Name: " + name);
})
})
$('#btnSelectAll').click(function() {
$('.row-select input').each(function() {
$(this).prop('checked', true);
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">12</td>
<td class="name">Jones</td>
</tr>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">10</td>
<td class="name">Joseph</td>
</tr>
</table>
<button id="btnSelectAll">Select all</button>
<button id="btnSubmit">Get Value</button>
Process step-by-step:
Give the td you need some classes (from-a & to-a);
Initialize an empty array all (we'll store the data inside it later on);
Create a function that is triggered by the checkbox change
Inside the function you need to know which checkbox has changed, what's the state of it, what tr does it belong to and at the end what are the TO AREA and FROM AREA values.
If the state = checked we will add the values to the all (our small data storage);
If the state = not-checked we will remove the value from the all array;
Finally when we are done with selecting and deselecting rows by pressing the button we can get the values of the selected rows.
var all = [];
$('input[type="checkbox"]').change(function(){
var checkbox = $(this);
var state = checkbox.prop('checked');
var tr = checkbox.parents('tr');
var from = tr.children('.from-a').text();
var to = tr.children('.to-a').text();
if(state){
all.push(from + ' -> ' + to);
}else{
var index = all.indexOf(from + ' -> ' + to);
all.splice(index, 1);
}
})
$('#get_to_area').click(function(){
alert(all);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox"></td>
<td>1</td>
<td>Nick</td>
<td class="from-a">Kosur</td>
<td class="to-a">Nath Pari</td>
<td>Address</td>
</tr>
<tr id="2">
<td><input type="checkbox"></td>
<td>2</td>
<td>John</td>
<td class="from-a">Rusok</td>
<td class="to-a">iraP htaN</td>
<td>sserddA</td>
</tr>
</tbody>
</table>
<center>
<div class="form-group">
<button style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
This is just the basic concept, you can modify it to suit your needs, I'll be happy to help you if you get stuck.
You can also use this fiddle:
In JS:
$('#get_to_area').click(function () {
var id = $('input[name=getchemist]:checked').val();
if ($('input[name=getchemist]').is(':checked')) {
var ID = $('input[name=getchemist]').parent().parent().siblings('td.chkid').html();
var TO_Area = $('input[name=getchemist]').parent().parent().siblings('td.toarea').html();
}
else {
alert('Please Check');
}
});
In Html:
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function (key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td class="chkid">' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td class="toarea">' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
I'm guessing you need values of each td whose checbox are checked. This piece of code should get you started.
As you can see, Code loops through each checkbox which is checked, gets contents inside its corresponding td.
var Result = new Array();
$('.checkbox-custom input[type="checkbox"]:checked').each(function(){
var _this = $(this).closest('tr').find('td');
var id= $(_this).eq(0);
var name = $(_this).eq(1);
................... //Similar way for the others
Result.Push(id,name,....)
});
I'm creating a userscript that collects and displays text from the following table using javascript / jQuery:
<table id="table-cours">
<tbody>
<tr>
<td class="calendar-time"> time1 </td>
<td>
<div class = popup-calendar-event> popup content 1 </div>
<div class = "link-event"> event 1 </div>
</td>
</tr>
<tr>
<td class="calendar-time"> time2 </td>
<td>
<div class = popup-calendar-event> popup content 2 </div>
<div class = "link-event"> event 2 </div>
</td>
</tr>
<tr>
<td class="calendar-time"> time3 </td>
<td>
<div class = popup-calendar-event> popup content 3 </div>
<div class = "link-event"> event 3 </div>
</td>
</tr>
</tbody>
</table>
I want to collect all the text contained in this table except that which is contained within the div.popup-calendar-event elements.
My objective is to display it like this:
time 1 : event 1
time 2 : event 2
time 3 : event 3
The problem is that the number of lines of the table can change, here I put 3 lines but they can be 1 or 10 or any other number.
I tried many ways like using the not() method, or a for() loop with an array of "tr" elements but it never works.
$('tr').each(function(data) {
var calTime = $(this).find('.calendar-time')[0].innerHTML;
var linkEvent = $(this).find('.link-event')[0].innerHTML;
$("#result").append('<li><b>' + calTime + '</b> : ' + linkEvent + '</li>');
console.log('<li><b>' + calTime + '</b> : ' + linkEvent + '</li>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="table-cours">
<tbody>
<tr>
<td class="calendar-time">time1</td>
<td>
<div class=p opup-calendar-event>popup content 1</div>
<div class="link-event">event 1</div>
</td>
</tr>
<tr>
<td class="calendar-time">time2</td>
<td>
<div class=p opup-calendar-event>popup content 2</div>
<div class="link-event">event 2</div>
</td>
</tr>
<tr>
<td class="calendar-time">time3</td>
<td>
<div class=p opup-calendar-event>popup content 3</div>
<div class="link-event">event 3</div>
</td>
</tr>
</tbody>
</table>
<ul id="result"></ul>
You can use something like this to parse table content and obtain an array of objects
var data = $('#table-cours > body > tr').map(function($i, $r) {
var $row = $(this);
return {
title: $row.find('.calendar-time').text(),
event: $row.find('.link-event').text()
};
}).get();
After that you can use data array for whatever you need.
You can try something like
$(".calendar-time").each(function () {
console.log($(this).html() + '-' + $(this).next('td').find('.link-event').html());
});
fiddle demo-http://jsfiddle.net/bL644p7b/
$(function(){
$("#table-cours .popup-calendar-event").each(function(iter, item){
$(".result").append("<div> time "+(iter+1) +" "+ $(this).text() +"</div>");
});
});
You just each a each method to iterate. The first argument is the iterator.
http://jsfiddle.net/qufgyh3c/
var rows = $('#table-cours > tr');
var map = {};
rows.each(function(row){
var key = $(row).find('td.calendar-time');
var value = $(row).find('td > div.link-event');
map[key]=value;
});
$(document).ready(function() {
$(".calendar-time").each(function() {
var output = "";
output += $(this).text() + " : ";
output += $(this).next().find(".link-event").text();
$(".output").append(output);
});
});
JSFiddle: https://jsfiddle.net/cq772j9s/
I would do:
$.each($('#table-cours tr'), function (i, val) {
$('#results ul').append('<li><strong>' + $(val).find('td.calendar-time').text() + '</strong>:' + $(val).find('.link-event').text() + '</li>');
});
example fiddle here
I trying to delete row from a table but somehow is not working. Could please let me know how can I solve this one ?
here is my html with table and javascript:
<tbody class="items">
<tr>
<td> Data 1 </td>
<td> Data 2 </td>
</tr>
</tbody>
<tbody id="test">
<tr>
<td> </td>
<td> </td>
</tr>
</tbody>
$(".items tr").click(function() {
var value = parseInt($.trim(tableData[1]));
$("#test").append(
"<tr><td><input name='sm_invnumber[]' value='" +
$.trim(tableData[0]) +
"' style='width: 170px;' readonly ></td><td><input name='sm_amount[]' value='" +
$.trim(tableData[1]) +
"' style='width: 170px; text-align: right;' readonly ></td><td><span onclick='deleteRow(value, this)'> x </span> </td></tr>");
});
function deleteRow(value, row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('#test').deleteRow(i);
}
Here is the instruction that I am working with: Picking data by clicking on table (class= items) and place to them into table (id=test). there is a function with 'X'. I want to delete this row.
Helps are highly appreciated.
You seem to making your life very difficult. Why not simply add a class to the cell that has the cross and use jQuery to remove its containing row. For example:
<table>
<tbody id="test">
<tr><td>Data 1</td><td class="delete">x</td></tr>
<tr><td>Data 2</td><td class="delete">x</td></tr>
<tr><td>Data 3</td><td class="delete">x</td></tr>
</tbody>
</table>
$('.delete').click(function () {
$(this).parent().remove();
});
Fiddle
try this
function deleteRow(value, span)
{
$(span).closest("tr").remove();
}
or
function deleteRow(value, span)
{
var i=row.parentNode.parentNode.rowIndex;
$(document.getElementById('test')).children(":eq("+i+")").remove();
}
There are few poblems, try
jQuery(function () {
var tableData = [1, 'test'];
$(".items tr").click(function () {
var value = parseInt($.trim(tableData[1]));
$("#test").append(
"<tr><td><input name='sm_invnumber[]' value='" + $.trim(tableData[0]) + "' style='width: 170px;' readonly ></td><td><input name='sm_amount[]' value='" + $.trim(tableData[1]) + "' style='width: 170px; text-align: right;' readonly ></td><td><span onclick='deleteRow(\"" + value + "\",this)'> x </span> </td></tr>");
});
})
function deleteRow(value, row) {
$(row).closest('tr').remove();
}
Demo: Fiddle, another version
With the SO community I have got a script that adds rows with unique names to a table. I want to take two inputs on each row and multiply them together and display result in a third input.
the fiddle is at http://jsfiddle.net/yUfhL/231/
My code is:
HTML
<table class="order-list">
<tr><td>Product</td><td>Price</td><td>Qty</td><td>Total</td></tr>
<tr>
<td><input type="text" name="product" /></td>
<td><input type="text" name="price" /></td>
<td><input type="text" name="qty" /></td>
<td><input type="text" name="linetotal" /></td>
</tr>
</table>
<div id="grandtotal">
Grand Total Here
</div>
JS
var counter = 1;
jQuery("table.order-list").on('change','input[name^="product"]',function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" name="product' +
counter + '"/></td><td><input type="text" name="price' +
counter + '"/></td><td><input type="text" name="qty' +
counter + '"/></td><td><input type="text" name="total' +
counter + '"/></td><td><a class="deleteRow"> x </a></td></tr>');
jQuery('table.order-list').append(newRow);
});
jQuery("table.order-list").on('click','.deleteRow',function(event){
$(this).closest('tr').remove();
});
$('table.order-list tr').each(function() {
var price = parseInt( $('input[id^=price]', this).val(), 10 );
var qty = parseInt( $('input[id^=qty]' , this).val(), 10 );
$('input[id^=linetotal]', this).val(price * qty);
});
So currently I cant get the js to fire that gets the product of the two cells, qty and price. I want to display result in linetotal.
The last part of this would be to display the sum of all linetotals as a grand total in the div grandtotal
Help appreciated as always.
You're only giving the elements a name attribute, but using the id selector ([id^=price]). It's much easier to give them a specific class than having to use that "id starts with" selector. Also, when do you want the line totals to be calculated? And when do you want the grand total to be calculated? On what event(s)?
Here's my interpretation of how it should look:
<table class="order-list">
<thead>
<tr><td>Product</td><td>Price</td><td>Qty</td><td>Total</td></tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="product" /></td>
<td>$<input type="text" name="price" /></td>
<td><input type="text" name="qty" /></td>
<td>$<input type="text" name="linetotal" readonly="readonly" /></td>
<td><a class="deleteRow"> x </a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: center;">
<input type="button" id="addrow" value="Add Product" />
</td>
</tr>
<tr>
<td colspan="5">
Grand Total: $<span id="grandtotal"></span>
</td>
</tr>
</tfoot>
</table>
And the JS:
$(document).ready(function () {
var counter = 1;
$("#addrow").on("click", function () {
counter++;
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" name="product' + counter + '"/></td>';
cols += '<td>$<input type="text" name="price' + counter + '"/></td>';
cols += '<td><input type="text" name="qty' + counter + '"/></td>';
cols += '<td>$<input type="text" name="linetotal' + counter + '" readonly="readonly"/></td>';
cols += '<td><a class="deleteRow"> x </a></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
});
$("table.order-list").on("change", 'input[name^="price"], input[name^="qty"]', function (event) {
calculateRow($(this).closest("tr"));
calculateGrandTotal();
});
$("table.order-list").on("click", "a.deleteRow", function (event) {
$(this).closest("tr").remove();
calculateGrandTotal();
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
var qty = +row.find('input[name^="qty"]').val();
row.find('input[name^="linetotal"]').val((price * qty).toFixed(2));
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="linetotal"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
http://jsfiddle.net/QAa35/
In your JS, you weren't using linetotal for the one dynamic input's name. There were other several minor modifications I made. You might as well use <thead>, <tbody> and <tfoot> since you do have those sections in the <table>. Also, I don't think it's a good design to have a new row automatically added when the "product" inputs are changed. That can happen often, and their intent may not be to add a new product...a button is much more friendly. For example, say you type in "asdf" to the first "product" input, then click somewhere. A new row is added. Say you made a typo so you go back and change it to "asd", then click somewhere. Another new row is added. That doesn't seem right.
This function should do the trick:
function updateGrandTotal() {
var prices = [];
$('input[name^="price"]').each(function () {
prices.push($(this).val());
});
var qnts = [];
$('input[name^="qty"]').each(function () {
qnts.push($(this).val());
});
var total = 0;
for(var i = 0; i < prices.length; i++){
total += prices[i] * qnts[i];
}
$('#grandtotal').text(total.toFixed(2));
}
You just need to bind it to the table change event to update the grand total every time an input changes:
$("table.order-list").change(updateGrandTotal);
Here is a working fiddle.