how to clone/copy html table using javascript/jquery [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I have a problem here, that when I click the copy button on the recently copied row. It doesnt work. You guys know how to fix this?
This is my code
var controller = function(num1) {
$('#copy-' + num1).click(function() {
var $tableBody = $('#table_name').find("tbody"),
$trLast = $tableBody.find("#tr-" + num1),
$trNew = $trLast.clone();
// $trNew.find('input').val('');
$trLast.after($trNew);
console.clear()
// refresh_index();
});
}
function refresh_index() {
$('#table_name > tbody > tr').each(function(i) {
i++;
var select = $(this).find('select');
var text = $(this).find('input');
var button = $(this).find('button');
controller(i);
});
}
refresh_index();
This is my code in JSFIDDLE

To attach the click event on dynamically created element use the delegation approach using .on(). This will allow the event to work on the elements those are added in the body at a later time.
Change
$('#copy-' + num1).click(function() {
To
$('body').on('click','#copy-'+num1, function() {
$(function(){
var controller = function(num1){
$('body').on('click','#copy-'+num1, function() {
var $tableBody = $('#table_name').find("tbody"),
$trLast = $tableBody.find("#tr-"+num1),
$trNew = $trLast.clone();
// $trNew.find('input').val('');
$trLast.after($trNew);
console.clear()
// refresh_index();
});
}
function refresh_index(){
$('#table_name > tbody > tr').each(function (i) {
i++;
var select = $(this).find('select');
var text = $(this).find('input');
var button = $(this).find('button');
controller(i);
});
}
refresh_index();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_name">
<thead>
<tr>
<th>No</th>
<th>Item</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="trs" id="tr-1">
<td>1</td>
<td>Mouse</td>
<td><button class="copy" id="copy-1">Copy</button></td>
</tr>
<tr class="trs" id="tr-2">
<td>2</td>
<td>Keyboard</td>
<td><button class="copy" id="copy-2">Copy</button></td>
</tr>
<tr class="trs" id="tr-3">
<td>3</td>
<td>Monitor</td>
<td><button class="copy" id="copy-3">Copy</button></td>
</tr>
</tbody>
</table>

You are adding it after the dom is loaded so it will not find it. If you use the on function to target something that was in the dom before it was dynamically added then add the target in the second variable after "click" then it should work.
$(function(){
var controller = function(num1){
var newThingy = '#copy-' + num1;
$("#table_name").on("click", newThingy, function() {
var $tableBody = $('#table_name').find("tbody"),
$trLast = $tableBody.find("#tr-"+num1),
$trNew = $trLast.clone();
// $trNew.find('input').val('');
$trLast.after($trNew);
console.clear()
// refresh_index();
});
}
function refresh_index(){
$('#table_name > tbody > tr').each(function (i) {
i++;
var select = $(this).find('select');
var text = $(this).find('input');
var button = $(this).find('button');
controller(i);
});
}
refresh_index();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table id="table_name">
<thead>
<tr>
<th>No</th>
<th>Item</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="trs" id="tr-1">
<td>1</td>
<td>Mouse</td>
<td><button class="copy" id="copy-1">Copy</button></td>
</tr>
<tr class="trs" id="tr-2">
<td>2</td>
<td>Keyboard</td>
<td><button class="copy" id="copy-2">Copy</button></td>
</tr>
<tr class="trs" id="tr-3">
<td>3</td>
<td>Monitor</td>
<td><button class="copy" id="copy-3">Copy</button></td>
</tr>
</tbody>
</table>

Use delegate event like $tableBody.find('.copy').off('click').on('click',function(){}); and bind click event after cloning the tr better to use class instead of ids. Here is the updated code based on your jsfiddle.
var $tableBody = $('#table_name').find("tbody");
clickEvent();
function clickEvent(){
$tableBody.find('.copy').off('click').on('click',function() {
$trLast = $(this).closest('tr'),
$trNew = $trLast.clone();
$trLast.after($trNew);
clickEvent();
});
function refresh_index(){
$('#table_name > tbody > tr').each(function (i) {
i++;
var select = $(this).find('td').eq(0).text(i);
});
}
refresh_index();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_name">
<thead>
<tr>
<th>No</th>
<th>Item</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="trs" id="tr-1">
<td>1</td>
<td>Mouse</td>
<td><button class="copy" id="copy-1">Copy</button></td>
</tr>
<tr class="trs" id="tr-2">
<td>2</td>
<td>Keyboard</td>
<td><button class="copy" id="copy-2">Copy</button></td>
</tr>
<tr class="trs" id="tr-3">
<td>3</td>
<td>Monitor</td>
<td><button class="copy" id="copy-3">Copy</button></td>
</tr>
</tbody>
</table>

Related

Make the whole row as a link with JS / jQuery

I want to achieve this situation with Javascript / jQuery. I want to write code that will use this a href and wrap-around tr
This is an example:
<tr>
<td>122880</td>
<td>John</td>
<td>Doe</td>
<td>More</td>
</tr>
I want to achieve this:
<tr data-href="/preson/details/42838">
<td>122880</td>
<td>John</td>
<td>Doe</td>
<td>More</td>
</tr>
Can anybody try to help me with this:
UPDATE
var elements = document.querySelectorAll('tr a');
Array.prototype.forEach.call(elements, function (el) {
el.href = el.href;
var new = document.querySelectorAll('tr');
Array.prototype.forEach.call(new, function (e) {
e.href= e.href.prop("data-href", el.href)
});
With jQuery, it's as simple as :
$("tr").each( function() {
const $tr = $(this);
$tr.attr("data-href", $tr.find("a").attr("href"));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>122880</td>
<td>John</td>
<td>Doe</td>
<td>More</td>
</tr>
</tbody>
</table>

How to remove matched record from both table using jquery

I am trying to remove matched record from both table if i click remove. Here matching except last column only because last column remove button. My code is not working: if I click remove all matched tr removing but I want which row I have clicked remove button in both tables that matched row only remove. How can I do it?
Code: https://jsfiddle.net/d4yzrtwn/3/
$(function(){
$('.remove').on('click', function(e){
$('#T1 tbody tr').each(function(){
var row = $(this);
var left_cols = $(this).find("td").not(':last');
$('#T2 tbody tr').each(function(){
var right_cols = $(this).find("td").not(':last');
if(left_cols.html() == right_cols.html()) {
$(this).closest('tr').remove();
}
});
$(this).closest('tr').remove();
});
});
});
Compare html content based on selected row's table with correspondent table.
Selection is dynamic, meaning works visa-versa and restricts remove on non-matching records.
$(function() {
$('.remove').click(function() {
let clicked_row = $(this).closest('tr');
let clicked_table = clicked_row.closest('table tbody').find('tr');
clicked_table.each(function() {
if (clicked_row.closest('table').attr('id') === 'T1') {
opponent_table = $('#T2 tbody tr');
} else {
opponent_table = $('#T1 tbody tr');
}
opponent_table.each(function() {
if ($(this).html() === clicked_row.html()) {
$(this).remove();
clicked_row.remove();
}
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<table id="T1" border='1'>
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Suffix</th>
</tr>
</thead>
<tbody>
<tr>
<td>12</td>
<td>34</td>
<td>56</td>
<td><span class="remove">Remove</span></td>
</tr>
<tr>
<td>12</td>
<td>84</td>
<td>96</td>
<td><span class="remove">Remove</span></td>
</tr>
<tr>
<td>bat</td>
<td>man</td>
<td>11</td>
<td><span class="remove">Remove</span></td>
</tr>
</tbody>
</table>
<br>
<table id="T2" border='1'>
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Suffix</th>
</tr>
</thead>
<tbody>
<tr>
<td>12</td>
<td>34</td>
<td>56</td>
<td><span class="remove">Remove</span></td>
</tr>
<tr>
<td>bat</td>
<td>man</td>
<td>11</td>
<td><span class="remove">Remove</span></td>
</tr>
<tr>
<td>james</td>
<td>bond</td>
<td>007</td>
<td><span class="remove">Remove</span></td>
</tr>
<tr>
<td>12</td>
<td>34</td>
<td>56</td>
<td><span class="remove">Remove</span></td>
</tr>
</tbody>
</table>
jsfiddle here: https://jsfiddle.net/debendraoli/qvy0dLfh/33/
#cinan
This code will do the job. It's more clear and readable. If you have any further questions please let me know.
$(function(){
$('.remove').on('click', function(e) {
var $removedRow = $(this).closest('tr');
var removedRowHtml = $removedRow.html();
var $clickedTable = $(this).closest('table');
var $anotherTable = $('table').not($clickedTable);
$('tr', $anotherTable).each(function(k, entry) {
if ($(entry).html() === removedRowHtml) {
$(entry).remove();
}
});
$removedRow.remove();
});
});
You can check it here as well: https://codepen.io/anon/pen/RdpMQP
$(function(){
$('.remove').on('click', function(e){
var content = $(e.currentTarget).closest("tr").text().trim();
$("#T1 tbody tr, #T2 tbody tr").each(function(e){
if($(this).text().trim() === content){
$(this).remove();
}
});
});
});
change your script to this. you don't have to do that all checks

How To Sum All Table Rows td (TotalPrice) using td id Jquery

I am adding values to table like:
Item,Quantity,Price,TotalPrice
Now there are multiple rows: How can i sum TotalPrice of all to get GrandTotal using Jquery.
Code:
$("#Product").append(" <tr><td id='clientname'>" +ClientName+ "</td> <td id='item'>"+ItemName+"</td> <td id='quantity'>"+Quantity+"</td> <td id='price'>"+Price+"</td> <td id='totalprice'>"+TotalPrice+"</td> <td> <a onClick='deleteRow(this);'>Delete</a> </td> </tr>");
Its possible when i insert new row data its show grand total in textbox/label,Like:
function TotalPriceCalc()
{
var lblTotalPrice = document.getElementById('lblTotalPrice');
lblTotalPrice.value = sum;
}
Here's an example that will sum whatever column index you provide.
$(function() {
$("#subtotal").html(sumColumn(4));
$("#total").html(sumColumn(5));
});
function sumColumn(index) {
var total = 0;
$("td:nth-child(" + index + ")").each(function() {
total += parseInt($(this).text(), 10) || 0;
});
return total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="border-spacing: 10px;">
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>12</td>
<td>34</td>
</tr>
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>56</td>
<td>78</td>
</tr>
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>90</td>
<td>12</td>
</tr>
<tr>
<td colspan="3">Totals</td>
<td id="subtotal"></td>
<td id="total"></td>
</tr>
</table>
After you use class= instead of id= .Cause ID MUST be unique. you need to loop through each row and find totalPrice
$(document).ready(function(){
var TotalValue = 0;
$("#Product tr").each(function(){
TotalValue += parseFloat($(this).find('.totalprice').text());
});
alert(TotalValue);
});
While you tagged Jquery .. This is a Jquery solution so please be sure to include Jquery
You should use classes, not IDs, to name repeated elements. So it should be:
...<td class="totalprice">'+TotalPrice+'</td>...
Then you can do
function TotalPriceCalc() {
var total = 0;
$(".totalprice").each(function() {
total += parseFloat($(this).text());
});
$("#lblTotalPrice").val(total);
}
Have look, this is our table
<table class="table table-bordered">
<thead>
<tr>
<th>1</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td id="loop">50</td>
</tr>
<tr>
<td>1</td>
<td id="loop">60</td>
</tr>
<tr>
<td>1</td>
<td id="loop">70</td>
</tr>
</tbody>
<tbody>
<tr>
<td class="text-right">Total</td>
<td></td>
</tr>
</tbody>
And this is loop to have sum of price
$(function() {
var TotalValue = 0;
$("tr #loop").each(function(index,value){
currentRow = parseFloat($(this).text());
TotalValue += currentRow
});
console.log(TotalValue);
});

jqQuery find cell value, if exists change cell, if not add new row

Any help would be greatly appreciated.
What I'm trying to achieve is when a number/text in input into the code box it searches the table, if found increments quantity by one, if not found adds a new row counting the no column by one.
I already a some basic jQuery code.
<input type="text" style="width: 200px" id="code" name="code" />
<input id = "btnSubmit" type="submit" value="Release"/>
<table> <thead>
<tr>
<th>No</th>
<th>Code</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>4444</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>5555</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>6666</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>7777</td>
<td>1</td>
</tr>
</tbody>
</table>
edit: my code.
$(document).ready(function() {
$("#btnSubmit").click(function() {
var code = $("input#code").val()
var table = $("table tbody");
table.find('tr').each(function(i) {
no = $(this).find('td').eq(0).text(),
productId = $(this).find('td').eq(1).text(),
Quantity = $(this).find('td').eq(2).text();
if (productId == code) { //see if product is in table
Quantity = +Quantity + +Quantity; // increase qty
alert('found' + Quantity); 
} else {
// Add new row
alert('not found');
}
});
});
});
I put together a JSFiddle for you, and copied the JS code here. I tried to make it as beginner friendly as possible...
$("#btnSubmit").on("click", function(){
numRows = $("tr").length;
for(var i=1 ; i<numRows ; i++){
var code = $("tr:nth-child(" + i + ") td:nth-child(2)").html();
var qty = $("tr:nth-child(" + i + ") td:nth-child(3)").html();
if(code == $("#code").val()){
$("tr:nth-child(" + i + ") td:nth-child(3)").html(parseInt(qty) + 1);
return true;
}
}
$("tbody").append("<tr><td>" + numRows + "</td><td>" + $("#code").val() + "</td><td>1</td></tr>");
return true;
});
I have created a sample code using jQuery. It took me like 10 minutes to figure out what you are trying to achive but I hope I understood you quite well:
HTML Side:
<input type="text" style="width: 200px" id="code" name="code" />
<input id = "btnSubmit" type="submit" value="Release"/>
<table> <thead>
<tr>
<th>No</th>
<th>Code</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>4444</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>5555</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>6666</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>7777</td>
<td>1</td>
</tr>
</tbody>
</table>
and our JavaScript:
$(document).ready(function() {
var found = false;
$("input#btnSubmit").on("click", function() {
var search_val = $("input#code").val();
$("tr").each(function() {
var obj = $(this);
obj.find("td").each(function() {
if(parseInt($(this).html()) == parseInt(search_val))
{
obj.find("td:nth-of-type(3)").html(parseInt(obj.find("td:nth-of-type(3)").html()) + 1);
found = true;
}
});
})
if(found == false)
{
$("table").append("<tr><td>"+($("tr").length)+"</td><td>"+search_val+"</td><td>1</td></tr>");
}
found = false;
});
});
Here's JSFiddle: http://jsfiddle.net/f17gudfw/4/

How to find custom elements in form and replece them to inputs

How to find all custom elements in form and convert it to inputs with same value?
Here is the example code: http://jsfiddle.net/irider89/jsL28xno/4/
$(function() {
$(".triggeredit-card-list").click(function() {
var UsrName = $('.card-list-table').find('#nameEditable').html();
console.log(UsrName);
$('.card-list-tabe').find('#nameEditable').html('<input type="text" class="editable-table" name="editname" id="edittext" value="'+ UsrName +'" />');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="flip-scroll" class="table-responsive card-list-table">
<table class="table table-custom">
<thead>
<tr>
<th>Номер карты</th>
<th>Ф.И.О.</th>
<th>Дата выдачи</th>
<th>Состояние</th>
<th>Сумма на карте</th>
<th>Категория</th>
<th>Суточная норма</th>
<th>Месячная норма</th>
<th>Выбранная норма за месяц</th>
<th>Вес карты</th>
<th>Комментарий</th>
</tr>
</thead>
<tbody>
<tr>
<td>5757427</td>
<td class="" id="nameEditable">Петров Иван Иванович 1</td>
<td>25.12.2013</td>
<td>Все</td>
<td>3 300</td>
<td>Дизель</td>
<td>123</td>
<td>26</td>
<td id="monthValue">1</td>
<td>2</td>
<td>Комментарий</td>
<td>
</td>
</tr>
<tr>
<td>69594894</td>
<td id="nameEditable">Константинопольский Яков Аристархович</td>
<td>27.12.2013</td>
<td>Все</td>
<td>3 300</td>
<td>123</td>
<td>123</td>
<td>25</td>
<td>1</td>
<td>2</td>
<td>Комментарий</td>
<td>
</td>
</tr>
<tr>
<td>5757427</td>
<td id="nameEditable">Петров Иван Иванович</td>
<td>25.12.2013</td>
<td>Все</td>
<td>3 300</td>
<td>123</td>
<td>123</td>
<td>25</td>
<td>1</td>
<td>2</td>
<td>Комментарий</td>
<td>
</td>
</tr>
</tbody>
</table>
</form>
<button class="btn btn-info btn-triggeredit triggeredit-card-list"><i class="glyphicon glyphicon-pencil"></i> Редактировать</button>
I need to convert to input Ф.И.О. and Выбранная норма за месяц, but to put this values to the input.
I would use nameEditable as class because you have multiple element with this marker on document and ended up with something like this:
$(function () {
$(".triggeredit-card-list").click(function () {
$('.nameEditable').each(function(index, item){
var content = $(item).html();
$(item).replaceWith('<input type="text" class="editable-table" name="editname" id="edittext" value="' + content + '" />');
})
});
});
JSFiddle
$(function () {
$(".triggeredit-card-list").click(function () {
$('.nameEditable').each(function(index, item){
var content = $(item).html();
$(item).replaceWith('<input type="text" class="editable-table" name="editname" id="edittext" value="' + content + '" />');
})
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="flip-scroll" class="table-responsive card-list-table">
<table class="table table-custom">
<thead>
<tr>
<th>Номер карты</th>
<th>Ф.И.О.</th>
<th>Дата выдачи</th>
<th>Состояние</th>
<th>Сумма на карте</th>
<th>Категория</th>
<th>Суточная норма</th>
<th>Месячная норма</th>
<th>Выбранная норма за месяц</th>
<th>Вес карты</th>
<th>Комментарий</th>
</tr>
</thead>
<tbody>
<tr>
<td>5757427</td>
<td class="nameEditable">Петров Иван Иванович 1</td>
<td>25.12.2013</td>
<td>Все</td>
<td>3 300</td>
<td>Дизель</td>
<td>123</td>
<td>26</td>
<td id="monthValue">1</td>
<td>2</td>
<td>Комментарий</td>
<td>
</td>
</tr>
<tr>
<td>69594894</td>
<td class="nameEditable">Константинопольский Яков Аристархович</td>
<td>27.12.2013</td>
<td>Все</td>
<td>3 300</td>
<td>123</td>
<td>123</td>
<td>25</td>
<td>1</td>
<td>2</td>
<td>Комментарий</td>
<td>
</td>
</tr>
<tr>
<td>5757427</td>
<td class="nameEditable">Петров Иван Иванович</td>
<td>25.12.2013</td>
<td>Все</td>
<td>3 300</td>
<td>123</td>
<td>123</td>
<td>25</td>
<td>1</td>
<td>2</td>
<td>Комментарий</td>
<td>
</td>
</tr>
</tbody>
</table>
</form>
<button class="btn btn-info btn-triggeredit triggeredit-card-list"><i class="glyphicon glyphicon-pencil"></i> Редактировать</button>
its an example of one of your inputs, according to your jsFiddle
You should use replaceWith to replace the elemnt, html just changes the innerHtml of the element
$( "th:contains('Ф.И.О.')" ).replaceWith('<input value="Ф.И.О." />')
if you want just replace the content in th use
$( "th:contains('Ф.И.О.')" ).html('<input value="Ф.И.О." />')
In general it is
var itemToFind = 'Ф.И.О.'
$( "th:contains('"+itemToFind+"')" ).html('<input value="'+itemToFind+'" />')
If you want all th which have class editable to be replaced with input use the code below
$( "th.editable" ).each( function() {
$(this).html('<input value="'+$(this).text()+'" />')
});
I see that you already have given an id to the td you want to turn editable.
Select all td with id "nameEditable"
For each of those:
Cache the text
Create an input
Assign the cached text to the inputs val
Clear the td text
Append the created input to the td
It would be better if you give your button an id.
$("#btn").on("click", function () {
$("td#nameEditable").each(function () {
var txt = $(this).text();
var $tmpl = $("<input type='text' />");
$tmpl.val(txt);
$(this).text('');
$(this).append($tmpl);
});
});
Demo Fiddle: http://jsfiddle.net/jsL28xno/5/
Update:
If you want to search for particular text in th and then use that to convert that column to editable, then:
Search th containing the text
Store the index of that th
Use nth-child selector to select all td with the stored index (+1 actually)
Insert input as mentioned in the above code snippet
.
$("#btn").on("click", function () {
editColumn("Ф.И.О.");
editColumn("Выбранная норма за месяц");
});
function editColumn(whichColumn) {
var idx = $("table th:contains('" + whichColumn + "')").index() + 1;
$('table td:nth-child(' + idx + ')').each(function() {
var txt = $(this).text();
var $tmpl = $("<input type='text' />");
$tmpl.val(txt);
$(this).text('');
$(this).append($tmpl);
});
}
Demo Fiddle 2: http://jsfiddle.net/5rdq5s43/1/
Note 1: Instead of searching for text, you could directly use the column number.
Note 2: It is advisable to provide each input you add, a unique id. You can do that by using the index of the each function.

Categories