get the values of all cells in table row using jquery - javascript

I would like to get the values in each cell in table row which is selected using a checkbox.
Scenario: Whenever user clicks the show table button, my page is dynamically loaded with some data from tables, which has columns like checkbox, Item name, Item code, Quantity, Rejected and Accepted. Now I want to get the values of selected rows when the user clicks the button called "save".
<script type="text/javascript">
$(document).ready(function() {
$("#tablediv").hide();
$("#showTable").click(function(event){
$.post('PopulateTable',{grn : $('#grn').val()},function(responseJson) {
if(responseJson!=null){
$("#itemtable").find("tr:gt(0)").remove();
var table1 = $("#itemtable");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).html('<input type="checkbox" />');
rowNew.children().eq(1).text(value['itemname']);
rowNew.children().eq(2).text(value['itemcode']);
rowNew.children().eq(3).text(value['supplier']);
rowNew.children().eq(4).text(value['receivedqty']);
rowNew.children().eq(5).html('<input type="text" class="tb2"/>');
rowNew.children().eq(6).html('<input type="text" class="tb2"/>');
rowNew.children().eq(7).html('<input type="text" class="tb2"/>');
rowNew.appendTo(table1);
});
}
});
$("#tablediv").show();
});
});
<br/>
<div id="tablediv">
<table cellspacing="0" id="itemtable" align="center">
<tr>
<td><input type="checkbox" /></td>
<th scope="col">Item name</th>
<th scope="col">Item code</th>
<th scope="col">Supplier</th>
<th scope="col">Received qty</th>
<th scope="col">Accepted qty</th>
<th scope="col">Rejected qty</th>
<th scope="col">Remarks</th>
</tr>
</table>
</div>
$(document).ready(function(){
// code to read selected table row cell data (values).
$("#itemtable").on('click','.btnSelect',function(){
// get the current row
alert("i am inside select");
// get the current row
var currentRow=$(this).closest("tr");
var col1=currentRow.find("td:eq(0)").text(); // get SI no from checkbox
var col2=currentRow.find("td:eq(1)").text(); // get item name
var col3=currentRow.find("td:eq(2)").text(); // get item code
var col4=currentRow.find("td:eq(3)").text(); // get supplier
var col5=currentRow.find("td:eq(4)").text(); // get received qty
var col6=currentRow.find("td:eq(5)").text(); // get accepted qty
var col7=currentRow.find("td:eq(6)").text(); // get rejected qty
var col8=currentRow.find("td:eq(7)").text(); // get remarks
var data=col1+"\n"+col2+"\n"+col3+"\n"+col4+"\n"+col5+"\n"+col6+"\n"+col7+"\n"+col8;
alert(data);
});
});
<!--btnSelect is class of checkbox -->

I come across below exaple to get all value of table cell of checked row.
$('.chk').change(function () {
if($(this).is(':checked'))
{
$(this).closest('tr').find('td').each(
function (i) {
console.log($(this).text());
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tablediv">
<table border="1" id="itemtable" align="center">
<tr>
<th>check</th>
<th scope="col">Item name</th>
<th scope="col">Item code</th>
<th scope="col">Supplier</th>
<th scope="col">Received qty</th>
<th scope="col">Accepted qty</th>
<th scope="col">Rejected qty</th>
<th scope="col">Remarks</th>
</tr>
<tr>
<td><input type="checkbox" class="chk" ></td>
<td>Pencil</td>
<td>101</td>
<td>Supplier</td>
<td>10</td>
<td>5</td>
<td>5</td>
<td>Remarks</td>
</tr>
<tr>
<td><input type="checkbox" class="chk" ></td>
<td>Pen</td>
<td>102</td>
<td>Supplier</td>
<td>25</td>
<td>20</td>
<td>5</td>
<td>Remarks</td>
</tr>
</table>
</div>

First give "name" to your checkbox, such as :
<input type="checkbox" name="case[]" />
JS code:
var values = new Array();
$("#saveButton").click(function(){
$.each($("input[name='case[]']:checked"), function() {
var data = $(this).parents('tr:eq(0)');
values.push({ 'Item name':$(data).find('td:eq(1)').text(), 'Item code':$(data).find('td:eq(2)').text() , 'Supplier':$(data).find('td:eq(3)').text()});
});
console.log(JSON.stringify(values));
});
Please check out the EXAMPLE

Related

How can I target a table cell in the same row with jQuery?

I have a table with a single input field and an AJAX script that runs when the input field value is modified. This is all working well. I now need to extend this to insert a date into another cell in the same row, but now sure how to target this as the ID will have to be dynamic. Here's the current table:
<table class="table table-condensed table-striped table-bordered">
<thead>
<th class="text-center" scope="col">Order Number</th>
<th class="text-center" scope="col">Order Date</th>
<th class="text-center" scope="col">Con Note</th>
</thead>
<tbody>
<tr>
<td>123456</td>
<td id="85759.OrderDate"></td>
<td id="85759"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
<tr>
<td>987654</td>
<td id="85760.OrderDate"></td>
<td id="85760"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
</tbody>
</table>
I need to insert the current data into the Order Data cell when the AJAX script is run, something like this:
$("#85759.OrderDate").html('current date');
but not sure how to dynamically target the Order Data cell? I'm setting the ID for the Order Data cell to be the same ID as the input field with ".OrderDate" appended. Current script is:
$(document).ready(function() {
$("input[type='text']").change(function() {
var recid = $(this).closest('td').attr('id');
var conNote = $(this).val();
$this = $(this);
$.post('updateOrder.php', {
type: 'updateOrder',
recid: recid,
conNote: conNote
}, function(data) {
data = JSON.parse(data);
if (data.error) {
var ajaxError = (data.text);
var errorAlert = 'There was an error updating the Con Note Number - ' + ajaxError;
$this.closest('td').addClass("has-error");
$("#serialNumberError").html(errorAlert);
$("#serialNumberError").show();
return; // stop executing this function any further
} else {
$this.closest('td').addClass("has-success")
$this.closest('td').removeClass("has-error");
}
}).fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an error updating the Con Note Number - AJAX request error. HTTP Status: ' + httpStatus;
$this.closest('td').addClass("has-error");
//display AJAX error details
$("#serialNumberError").html(ajaxError);
$("#serialNumberError").show();
});
});
});
You can get the parent element 'tr' and then find the 'td.OrderDate', I suggest you to use a class to identify the td in the context of its parent.
$(function () {
$("input[type='text']").change(function() {
var parent = $(this).parents('tr');
// Get any element inside the tr
$('td.OrderDate', parent).text('[current date]')
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>987654</td>
<td id="85760.OrderDate" class="OrderDate"></td>
<td id="85760"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
</table>
You can select the cell by $this.closest('tr').children('td[id$="OrderDate"]').
You can simplify it more by:
Instead of using attribute ends with selector ([id$=".."]), if you can, add a CSS class "OrderDate" for example to all the order date cells, and simplify the selector to $this.closest('tr').children('.OrderData')
Instead of closest() use parents(). This is a micro-optimization. The only difference is that closest tests the actual element itself for matching the selector, and in this case you know you only need to check parent elements
You can also optionally rely on the fact that the cells are siblings and instead of children use siblings like like$this.parents('td').siblings('.OrderDate')
Check the code below. I've removed the ajax call and replaced it with the success block, but the concept is still the same. It gets the cell that has an id that ends with "OrderDate" on the same row and sets the html for that cell. I've used the jQuery Ends With selector for this.
$(document).ready(function() {
$("input[type='text']").change(function() {
var recid = $(this).closest('td').attr('id');
var conNote = $(this).val();
var $this = $(this);
$this.parents('tr:first').find("td[id$='OrderDate']").html(new Date());
$this.closest('td').addClass("has-success")
$this.closest('td').removeClass("has-error");
});
});
.has-success {
border: 1px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed table-striped table-bordered">
<thead>
<th class="text-center" scope="col">Order Number</th>
<th class="text-center" scope="col">Order Date</th>
<th class="text-center" scope="col">Con Note</th>
</thead>
<tbody>
<tr>
<td>123456</td>
<td id="85759.OrderDate"></td>
<td id="85759"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
<tr>
<td>987654</td>
<td id="85760.OrderDate"></td>
<td id="85760"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
</tbody>
</table>

Select multiple rows in a table filled by a Servlet

Sorry for my noob question, but I have a table filled by a servlet on my JSP page:
Table
<table id="tableusers" class="table table-striped table-bordered bootstrap-datatable datatable">
<thead>
<tr>
<th>Nom</th>
<th>Prénom</th>
<th>Adresse</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
JavaScript
$.get('/SRV/webUserServlet', function(responseJson) {
if (responseJson != null) {
var table1 = $("#tableusers");
$.each(responseJson, function(key, value) {
var rowNew = $("<tr><td></td><td class=\"center\"></td><td class=\"center\"></td><td class=\"center\"></td></tr>");
rowNew.children().eq(0).text(value['nom']);
rowNew.children().eq(1).text(value['prenom']);
rowNew.children().eq(2).text(value['adresse']);
rowNew.children().eq(3).text(value['email']);
rowNew.appendTo(table1);
});
}
});
Table is filled correctly but I tried multiple jQuery javascripts to select multiple rows from this table and send the result of the select lines to another servlet but unfortunately as the content is dynamic, I'm not able to make any JS script functional.
How can I select one, or multiple (or all) rows and send the selected lines (with all the columns) to a servlet ?
When you are building the table, assign classes and / or id's to the td's that you want the values from. You can then use jquery to select off of an id, for instance, instead of selecting off of a value.
<table id="tableusers" class="table table-striped table-bordered bootstrap-datatable datatable">
<thead>
<tr class="columns">
<th id="col1">Nom</th>
<th id="col2">Prénom</th>
<th id="col3">Adresse</th>
<th id="col4">email</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
Then you can select the values like this:
$("#col1").text();
or like this:
$("tr.columns th").each(function() {
$(this).text();
});
Apply the same principle to rows in the body if you are wanting those values too.
There is no relation with servlet, you only have a javascript problem.
Write a simple page in raw HTML, include your js code and load your page in a browser with developpers tools activated. Debug and look at which URLs are called. Once you'll have resolved this problem you will try to integrate the solution in your JSP.
Finally I'm parsing my table using DOM:
var table = document.getElementById('tabletest');
var rowLength = table.rows.length;
for(var i=1; i<rowLength; i+=1){
var row = table.rows[i];
var cellLength = row.cells.length;
if(row.cells[0].getElementsByTagName('input')[0].checked==true){
console.log("checked");
console.log("cellule: "+row.cells[1].innerHTML);
}
}
could be interesting for people who have the same problem than me....but without JQuery.
by the way, it works only with a static table content. when I'm trying to parse the table dynamically filled by the servlet, the if statement
if(row.cells[0].getElementsByTagName('input')[0].checked==true)
is generating an error (input undefined) but by looking at the table values, the row.cells[0] contains:
cell[0]: <input type="checkbox">
I tried with a static table with the exact table structure:
<table id="tabletest" class="table table-striped table-bordered bootstrap-datatable datatable">
<thead>
<tr>
<th style="width:20px;"><input type="checkbox" id="checkall" title="Select all"></th>
<th>Nom</th>
<th>Prénom</th>
<th>Adresse</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"> </td>
<td>john</td>
<td>smith</td>
<td>12 rue des laures</td>
<td>john#tt.com</td>
</tr>
<tr>
<td><input type="checkbox"> </td>
<td>marcel</td>
<td>dib</td>
<td>13 rue des laures</td>
<td>marcel#tt.com</td>
</tr>
<tr>
<td><input type="checkbox"> </td>
<td>toto</td>
<td>titi</td>
<td>14 rue des laures</td>
<td>steph#tt.com</td>
</tr>
</tbody>
</table>
with the following script:
function checkSelectedUsers(){
var table = document.getElementById('tabletest');
var rowLength = table.rows.length;
for(var i=1; i<rowLength; i+=1){
var row = table.rows[i];
//console.log("row: "+row.innerHTML);
console.log("row:"+row.innerHTML);
console.log("cell[0]:"+row.cells[0].innerHTML);
console.log("cell[1]:"+row.cells[1].innerHTML);
if(row.cells[0].getElementsByTagName('input')[0].type == "checkbox")
console.log("Checkbox:"+row.cells[0].getElementsByTagName('input')[0].checked);
/* if(row.cells[0].getElementsByTagName('input')[0].checked==true){
console.log("checked");
console.log("cellule: "+row.cells[4].innerHTML);
}*/
}
}
I have the following in the logs console:
row:
<td><input type="checkbox"> </td>
<td>john</td>
<td>smith</td>
<td>12 rue des laures</td>
<td>john#tt.com</td>
cell[0]:<input type="checkbox">
cell[1]:john
Checkbox:false
row:
<td><input type="checkbox"> </td>
<td>marcel</td>
<td>dib</td>
<td>13 rue des laures</td>
<td>marcel#tt.com</td>
cell[0]:<input type="checkbox">
cell[1]:marcel
Checkbox:false
row:
<td><input type="checkbox"> </td>
<td>toto</td>
<td>titi</td>
<td>14 rue des laures</td>
<td>steph#tt.com</td>
cell[0]:<input type="checkbox">
cell[1]:toto
Checkbox:false
so my table is parsed correctly. But if I get the same JS function with the table generated with JQuery:
$(document).ready(function() {
$.get('/OrdolinkSRV/webUserServlet',function(responseJson) {
if(responseJson!=null){
var table1 = $("#tableusers");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td><input type=\"checkbox\"></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(1).text(value['nom']);
rowNew.children().eq(2).text(value['prenom']);
rowNew.children().eq(3).text(value['adresse']);
rowNew.children().eq(4).text(value['email']);
rowNew.appendTo(table1);
});
}
});
});
I have the following error :
row:
Uncaught TypeError: Cannot read property 'innerHTML' of undefined

Cloning row with independent values

I am having a few issues with something. I have the following two tables
<table id="customFields1" class="table table-bordered table-hover additionalMargin alignment">
<thead>
<tr>
<th colspan="2"></th>
<th>Some Title</th>
</tr>
</thead>
<tbody>
<tr>
<td><label class="subjectline" for="User1">User NOC M1</label></td>
<td id="slLabel">SL_A</td>
<td id="slInput"><input type="text" name="slOptions[User][NOC M1]" class="form-control" id="User1"></td>
<td><a class="addCF" href="javascript:void(0);">+ additional user</a></td>
</tr>
</tbody>
</table>
<table id="customFields2" class="table table-bordered table-hover additionalMargin alignment">
<thead>
<tr>
<th colspan="2"></th>
<th>Some Title</th>
</tr>
</thead>
<tbody>
<tr>
<td><label class="subjectline" for="User1">User NOC M1</label></td>
<td id="slLabel">SL_A</td>
<td id="slInput"><input type="text" name="slOptions[User][NOC M1]" class="form-control" id="User1"></td>
<td><a class="addCF" href="javascript:void(0);">+ additional user</a></td>
</tr>
</tbody>
</table>
Both of the have an addCF button. This is used to add a new row to the table. This is achieved through this
$(function() {
alp = "A";
regexp = /[_A]+$/;
$(".addCF").click(function(){
alp = (alp.substring(0,alp.length-1)+String.fromCharCode(alp.charCodeAt(alp.length-1)+1));
var clone = $(this).closest('tr').clone(true);
var inputOrgLabel = $("td:nth-child(2)", clone).html();
inputOrgLabel = inputOrgLabel.replace(regexp,'');
$("td:nth-child(2)", clone).html(inputOrgLabel+'_'+alp);
$("td:first-child", clone).empty();
$("td:last-child", clone).html('Remove');
clone.insertAfter($(this).closest('table').find('tr:last'));
});
$("table.table").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
Everything appears to work besides one thing. If I add a new row, I change the label SL_A to SL_B. Every row added has the next letter of the alphabet added to the end of it. This is working, but if I add a row in table 1, making it SL_B, and then add a row in table 2, the row in table 2 has SL_C. Each of the incrementations of letters should be independent, so the second row in table two should also have SL_B.
Is this possible? I have set up a JSFiddle to demonstrate
Thanks
I have made an array for holding your data in alp and changed accordingly. Here i ma getting the index of the clicked button to use that index as the index of the apl array.
$(function() {
alp = [];
$.each($('.addCF'), function(i,v) {
alp[i] = "A";
})
regexp = /[_A]+$/;
$(".addCF").click(function(e){
index = $('.addCF').index($(this));
alp[index] = (alp[index].substring(0,alp[index].length-1)+String.fromCharCode(alp[index].charCodeAt(alp[index].length-1)+1));
var clone = $(this).closest('tr').clone(true);
var inputOrgLabel = $("td:nth-child(2)", clone).html();
inputOrgLabel = inputOrgLabel.replace(regexp,'');
$("td:nth-child(2)", clone).html(inputOrgLabel+'_'+alp[index]);
$("td:first-child", clone).empty();
$("td:last-child", clone).html('Remove');
clone.insertAfter($(this).closest('table').find('tr:last'));
});
$("table.table").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
Note: You have to manage code for remove, as it is not resetting the value.

re-calculate every sum total of every row when radio change

Good day,
I have a dynamic table where you can add and remove table when you press X button, in each row there is a Current Qty field and Adjusted Qty field and also there is a New Qty field which is derived when you input a number on the Adjusted Qty Field, and its all working correctly but I want to add a functionality that will change every total Qty Field base on checked radio box above the table. Like if you click the IN (radio button), the operation will be ADD, and if you click the OUT (radio button), the operation will be MINUS and all the rows should be affected by every 'onchange' event of the radio button. Can anyone please help me :)
HTML:
<div class="col-xs-12">
<div class="box">
<div class="box-body table-responsive">
<div id="records">
<div class="form-group">
<label for="departments">Department</label>
<select name="departments" id="">
#foreach($departments as $department)
<option value="{{$department->xid}}">{{$department->department}}</option>
#endforeach
</select>
</div>
<br>
<label for="radio">Adjustment Type</label>
<div class="radio">
<label><input type="radio" class="adjType" value="in" id="radioIn" name="optradio">Inventory In</label>
</div>
<div class="radio">
<label><input type="radio" class="adjType" value="out" id="radioOut" name="optradio">Inventory Out</label>
</div>
</div>
<label for="remarks">Remarks</label>
<input type="text" name="remarks" required id="memo" placeholder="Text input" class="form-control">
<br>
<table class="table table-condensed" id="adjustmentTable">
<thead>
<tr>
<th width="30%">Item</th>
<th width="10%">Qty on Hand</th>
<th width="10%">Adjusted Qty</th>
<th width="10%">new Qty</th>
<th width="10%">Current Cost</th>
<th width="10%">Adjusted Cost</th>
<th width="10%">Cost Diff</th>
<th width="10%">Expiration Date</th>
<th width="10%">Remove</th>
</tr>
</thead>
<tbody>
<tbody>
<tr>
<td>Item 1</td>
<td>20</td>
<td>10</td>
<td>30</td>
<td>10.40</td>
<td>12.00</td>
<td>.60</td>
<td>11/21/1016</td>
<td>X</td>
</tr>
<tr>
<td>Item 31</td>
<td>230</td>
<td>16</td>
<td>246</td>
<td>31.40</td>
<td>20.00</td>
<td>-11.40</td>
<td>11/21/1019</td>
<td>X</td>
</tr>
<tr>
<td>Item 6</td>
<td>12</td>
<td>19</td>
<td>31</td>
<td>22.40</td>
<td>30.00</td>
<td>7.60</td>
<td>11/21/1016</td>
<td>X</td>
</tr>
</tbody>
</tbody>
</table>
JS:
<script>
var $this = $(document);
$this.on("change",'input[name="optradio"]',function(){
var rowCount = $('#adjustmentTable tr').length - 1;
});
You need to create event handlers for the "change" event on those radio buttons. These event handlers will then loop through all the rows of your table, and apply the AutoCalculateDifference function to each row. Something like this:
$("#radioIn, #radioOut").change(function() {
// The user clicked a radio button. Now loop through all the
// rows in the table. NOTE: You should be more specific with
// this jQuery selector to refer to the exact ID of the table.
$("table tr").each(function() {
autoCalculateDifferenceOnRow(this);
});
});
If you do this, then you will need to refactor your AutoCalculateDifference function a little bit to be able to handle an incoming parameter representing the row, rather than always using "this". For example,
function autoCalculateDifferenceOnRow(currentRow) {
if(document.getElementById('radioIn').checked) {
var type = 1;
}else if(document.getElementById('radioOut').checked) {
var type = 0;
}
var $adjQty = $(currentRow).find('.adjQty');
var $newCost = $(currentRow).find('.newCost');
var $onHandQty = $(currentRow).find('p.onHandQty');
var $qtyDiff = $(currentRow).find('p.qtydiff');
var $currentCost = $(currentRow).find('p.currentCost');
var $costDiff = $(currentRow).find('p.costDiff');
// Update Quantity
var onHandQty = parseInt($onHandQty.text(),10);
if(type == 1)
{
var difference = onHandQty + parseInt($adjQty.val());
}
else if(type==0)
{
var difference = onHandQty - parseInt($adjQty.val());
}
$qtyDiff.text(difference);
// Update Cost
var currentCost = $currentCost.text();
var difference = $newCost.val() - currentCost;
$costDiff.text(difference);
}
I haven't tested the above code, but hopefully it helps you head in the right direction.

How to copy the contents of one row in a table to another table and add the identical ones

var Sell_Button = document.getElementById('sellbtn'),
secondTable = document.getElementById("secondTableBody");
Sell_Button.addEventListener('click', function() {
var Row = secondTable.insertRow();
for (var c = 0; c < 2; c += 1) {
Row.insertCell(c);
}
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[2].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
//checks to see if the secondTable has a row containing the same name
for (var f = 0; f < secondTable.rows.length; f += 1) {
//adds only the sold amount if the second table has a row with the same name
//error
if (secondTable.rows[f].cells[0].innerText === this.parentNode.parentNode.cells[0].innerText) {
secondTable.rows[f].cells[1].innerHTML = +this.parentNode.parentNode.cells[2].innerHTML;
//deletes an extra row that is added at the bottom
if (secondTable.rows.length > 1) {
secondTable.deleteRow(secondTable.rows.length - 1);
}
//if nothing matched then a new row is added
} else {
secondTable.insertRow();
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[1].innerHTML = this.parentNode.parentNode.cells[2].innerHTML;
}
}
}
}
<html>
<body>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
</tbody>
</table>
</div>
</br>
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTableBody">
</tbody>
</table>
</div>
</body>
</html>
Ok, this example isn't exactly what i'm working on but it's very similar. The only difference is that in mine the rows and buttons are dynamically added by the user and he inserts the details. What I want is that when i press on the button of each row (sell) the details (Item and Sold only) are copied into a row in the second table and checks if the same item exists in this second table if so then it adds the amount of sold of both items in one row. For instance I press on the first row button the Apples it copies the listed above details to the second table in a row and then when i click on the button of the second row (Apples also) it only adds the sold amount up and doesn't add a second apples row because an apples row already exists in the second table but when i click on the oranges button it makes a new row because the oranges row doesn't exist. So how do I do this in JavaScript? i hope i was thorough and made any sense. I have no idea why the code isn't working here but i hope you get the point. This code works perfectly just as i want it to until for some reason i get this error: Cannot read property 'innerText' of undefined when i press the buttons approx. 6-7 times targeting the if statement where i commented error.
This sets a click handler to all buttons. If the row doesn't exist in the second table it's created. It sets a data-type referring to the item. When somebody clicks the sell button again and there is a row containing the data-type the row is updated instead of created. All in plain JavaScript.
var Sell_Button = document.querySelectorAll('.sellbtn'),
secondTable = document.getElementById("secondTableBody");
Array.prototype.slice.call(Sell_Button).forEach(function(element){
element.addEventListener('click', function(e) {
//since the button is an element without children use e.
var clickedElement = e.target;
var parentRow = clickedElement.parentNode.parentNode;
//check if second table has a row with data-type
var rowWithData = secondTable.querySelector("[data-type='"+parentRow.cells[0].childNodes[0].nodeValue+"']");
if (rowWithData)
{
rowWithData.cells[1].innerHTML = parseInt(rowWithData.cells[1].childNodes[0].nodeValue) + parseInt(parentRow.cells[2].childNodes[0].nodeValue);
}
else
{
var Row = secondTable.insertRow();
Row.setAttribute("data-type", parentRow.cells[0].childNodes[0].nodeValue);
for (var c = 0; c < 2; c += 1) {
Row.insertCell(c);
}
Row.cells[0].innerHTML = parentRow.cells[0].childNodes[0].nodeValue;
Row.cells[1].innerHTML = parentRow.cells[2].childNodes[0].nodeValue;
}
});
});
<html>
<body>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
</tbody>
</table>
</div>
</br>
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTableBody">
</tbody>
</table>
</div>
</body>
</html>
Do you mean something like:
$(document).on("click", "#firstTable tr button", function(b) {
b = $(this).closest("tr");
var d = $.trim(b.find("td:first").text());
b = parseFloat($.trim(b.find("td:nth-child(3)").text()));
var a = $("#secondTable"),
c = a.find("tr").filter(function(a) {
return $.trim($(this).find("td:first").text()) == d
});
c.length ? (a = c.find("td:nth-child(2)"), c = parseFloat($.trim(a.text())), a.text(b + c)) : (a = $("<tr />").appendTo(a), $("<td />", {
text: d
}).appendTo(a), $("<td />", {
text: b
}).appendTo(a))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<tr>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</tr>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td><button>Sell</button></td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td><button>Sell</button></td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td><button>Sell</button></td>
</tr>
</tbody>
</table>
</div>
<br />
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<tr>
<th>Item</th>
<th>Sold</th>
</tr>
</thead>
<tbody id="secondTableBody"></tbody>
</table>
</div>

Categories

Resources