Using same JS function for multiple HTML tables? - javascript

I have function which adds and delete rows of a table on click of a button i.e add_row. Now i have multiple tables and for which i want to use the same function on the same page.
So below function is for table1, how do i reuse the same function for table2,table3 .. etc? Each table will have its own add_row button i.e, add_row,add_row1, add_row2 etc..
<script type="text/javascript">
$(document).ready(function() {
var rowIdx = 0;
$('#add_row').on('click', function () {
$.each($("#table1 tr"), function() {
if (parseInt($(this).data("id")) > rowIdx) {
rowIdx = parseInt($(this).data("id"));
console.log(rowIdx)
}
});
rowIdx++;
$('#table1').append(`<tr id="addr${rowIdx}" data-id="${rowIdx}" class="hidden">
<td data-name="id">
<input type="text" name='id${rowIdx}' placeholder='ID' value=""`);
});
$('#table1').on('click', '.remove', function () {
var child = $(this).closest('tr').nextAll();
child.each(function () {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(4));
idx.html(`Row ${dig - 1}`);
$(this).attr('id', `addr${dig - 1}`);
});
$(this).closest('tr').remove();
rowIdx--;
}
);
});
</script>

You mean this?
Don't add and subtract from rowIndex. It is different per table. Use the actual number of rows in the specific table
$(function() {
$('.add_row').on('click', function() {
const $table = $(this).closest("table");
const $rows = $table.find("tr");
let rowIndex = $rows.length;
$table.append(`<tr id="addr${rowIdx}" data-id="${rowIdx}" class="hidden">
<td data-name="id"><input type="text" name='id${rowIdx}' placeholder='ID' value=""</td></tr>`);
});
$(document).on('click', '.remove', function() {
var child = $(this).closest('tr').nextAll();
child.each(function() {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(4));
idx.html(`Row ${dig - 1}`);
$(this).attr('id', `addr${dig - 1}`);
});
$(this).closest('tr').remove();
});
});

Related

How to change calculation when the row is removed from a table

My problem is the calculations are working fine but when the row is removed the calculations are not updating according to that after creating a new row and after performing calculation only the values are updating..please help me to rectify this problem.
$(document).on('change', 'tr td:nth-child(6), tr td:nth-child(5), tr td:nth-child(4)', .
'remove3'
function() {
var total = 0;
var sqty = 0;
var tr = $(this).parent();
var qty = tr.find('td:nth-child(4)').find('input').val();
var rate = tr.find('td:nth-child(5)').find('input').val();
var amount = qty * rate;
tr.find('td:nth-child(6)').find('input').val(amount);
var tbody = tr.parent();
$(tbody).find('tr').each(function() {
total += Number($(this).find('td:nth-child(6)').find('input').val());
sqty += Number($(this).find('td:nth-child(4)').find('input').val());
});
$('#TieTotal').val(total);
$('#SQty').val(sqty);
$('#Grandtot').val(total);
})
Script to create a next row automatically:
$('.tb3').on('keydown', 'input', function(e) {
var keyCode = e.keyCode;
if (keyCode !== 9) return;
var $this = $(this),
$lastTr = $('tr:last', $('.tb3')),
$lastTd = $('td:last', $lastTr);
if (($(e.target).closest('td')).is($lastTd)) {
var cloned = $lastTr.clone();
cloned.find('input').val('');
$lastTr.after(cloned);
}
});
Script to delete row:
$(document).on('click', '.remove3', function() {
var trIndex = $(this).closest("tr").index();
if (trIndex > 0) {
$(this).closest("tr").remove();
} else {
alert("Sorry!! Can't remove first row!");
}
});
Let's imagine you have an HTML like (could be a dynamically drawn HTML).
<tr>
<td><input class="Qty" type="text" value="2"/></td>
<td><input class="Rate" type="text" value="200"/></td>
<td><input class="Value" type="text"/></td>
<td><button type="button" class="remove3">X</button></td>
</tr>
Also, let's say you have changed the approach to update the total to be like this, (which is inside document ready). This is a sample code, your actual code may vary. All you need to do is keep the triggering on("keyup change") (or as however you like) inside the document.ready().
$('.Qty').on("keyup change",function(){
var $row = $(this).closest("tr");
var price = 0;
var total = 0;
$('.tb3 tr').each(function() {
var qty = $(this).find('.Qty').val();
var rate = $(this).find('.Rate').val();
var price = qty * rate;
$(this).find('.Value').val(price);
total += parseFloat(price);
});
$('#TieTotal').val(total.toFixed(2));
});
Now, when each time you press the button which has class .remove3 you are correct in terms of removing the row. In the same block you can easilty update the total by triggering the change() event of element which has the class .Qty. (That's how the total is updated in the first place) See below,
$('.remove3').click(function () {
var trIndex = $(this).closest("tr").index();
if (trIndex > 0) {
$(this).closest("tr").remove();
$('.Qty').trigger('change');
} else {
alert("Sorry!! Can't remove first row!");
}
});
Fiddle,
https://jsfiddle.net/anjanasilva/dykm6wau/
I hope this helps.
Cheers!
Update this line:
$(document).on('change', 'tr td:nth-child(6), tr td:nth-child(5), tr td:nth-child(4), .remove3' function(){
i think class '.remove3' not added properly with selectors list.
$(document).on('change', 'tr td:nth-child(6), tr td:nth-child(5), tr td:nth-child(4)', .
'remove3'
function() {
var total = 0;
var sqty = 0;
var tr = $(this).parent();
var qty = tr.find('td:nth-child(4)').find('input').val();
var rate = tr.find('td:nth-child(5)').find('input').val();
var amount = qty * rate;
tr.find('td:nth-child(6)').find('input').val(amount);
var tbody = tr.parent();
$(tbody).find('tr').each(function() {
total += Number($(this).find('td:nth-child(6)').find('input').val());
sqty += Number($(this).find('td:nth-child(4)').find('input').val());
});
$('#TieTotal').val(total);
$('#SQty').val(sqty);
$('#Grandtot').val(total);
})
Script to create a next row automatically:
$('.tb3').on('keydown', 'input', function(e) {
var keyCode = e.keyCode;
if (keyCode !== 9) return;
var $this = $(this),
$lastTr = $('tr:last', $('.tb3')),
$lastTd = $('td:last', $lastTr);
if (($(e.target).closest('td')).is($lastTd)) {
var cloned = $lastTr.clone();
cloned.find('input').val('');
$lastTr.after(cloned);
}
});
Script to delete row:
$(document).on('click', '.remove3', function() {
var trIndex = $(this).closest("tr").index();
if (trIndex > 0) {
$(this).closest("tr").remove();
$('.Qty').trigger('change');
} else {
alert("Sorry!! Can't remove first row!");
}
});

Code returns all the items in Checkboxes

In here i want to get allRefItems but it should be checked & NOT disabled.But in here always get
all the Id's
var allRefItems = [];
$('table#reftable > tbody > tr').each(function () {
if ($(this).find('td:eq(0) input', this).is(':checked')) {
if ($(this).find('td:eq(0) input', this).not(':disabled')) {
itId = $(this).find('td:eq(0) input', this).attr('id');
allRefItems.push(itId);
}
}
});
If you want to get all checkboxes in table i think you could do it easier:
var allRefItems = [];
$('table#reftable > tbody input[type="checkbox"]') //get all checboxes
.filter(function() { // filter them only checked and not disabled
return !this.disabled && this.checked;
}).each(function () { //getting your ids
itId = $(this).attr('id');
allRefItems.push(itId);
});
Here is an jsFiddle example.
You can use,
var allRefItems = $('table#reftable > tbody > tr input[type="checkbox"]:checked:not(:disabled)').map(function() {
return this.id;
}).get();

Find value in all TD with Highlighting

I have this script for searching in table with Highlighting value from "input". But only for first TD in all TR.
Function remove Highlighting
function removeHighlighting(highlightedElements){
highlightedElements.each(function(){
var element = $(this);
element.replaceWith(element.html());
})
}
Function add Highlighting
function addHighlighting(element, textToHighlight){
var text = element.text();
var highlightedText = '<em>' + textToHighlight + '</em>';
var newText = text.replace(textToHighlight, highlightedText);
element.html(newText);
}
Searching in table but only in first TD in TR
$("#search").on("keyup", function() {
var value = $(this).val();
removeHighlighting($("table tr em"));
$("table tr").each(function(index) {
if (index !== 0) {
$row = $(this);
var $tdElement = $row.find('td:first');
var id = $tdElement.text();
var matchedIndex = id.indexOf(value);
if (matchedIndex != 0) {
$row.hide();
}
else {
addHighlighting($tdElement, value);
$row.show();
}
}
});
});
I donĀ“t know how can I searching in all TD and How can I write e.g. some alert if "matchedIndex == -1" (if not found some value from input)
Try looping in all TDs of TR
$("table tr").each(function(index) {
if (index !== 0) {
row = $(this);
$("td", this).each(function(idx) {
var id = $(this).text(); //or $(this).innerText
var matchedIndex = id.indexOf(value);
if (matchedIndex != 0) {
$row.hide();
}
else {
addHighlighting($tdElement, value);
$row.show();
}
}
}
});
A short way
$("table tr > td em").each(function(){
$( this ).replaceWith( $( this ).text() );
});
Adding a span tag with a highlight class is the way to go like suggested in the comments.
Please find a working demo below and in this jsFiddle.
There is a really useful function to remove all the wrapping of the spans. You can do this with $('span.highlight').contents().unwrap().
For finding the text you can use string.search(searchText) or string.match(searchText). The search method will return -1 if nothing is found and the position of the text if found. And match would return occurences in the searchText.
For testing that it finds the first occurence I have added TestY in the table. The flag matched is responsible for this behavior. If you would remove it, it would highlight both TestY elements.
(function () {
var removeHighlight = function () {
$('span.highlight').contents().unwrap();
};
var wrapContent = function (index, $el, text) {
var $highlight = $('<span class="highlight"/>')
.text(text.substring(0, index));
//console.log(text.substring(0, index));
var normalText = document.createTextNode(text.substring(index, text.length));
//console.log(index, $highlight.text(), normalText);
$el.html($highlight).append(normalText);
};
var highlightTextInTable = function ($tableElements, searchText) {
// highlights if text found (during typing)
var matched = false;
//remove spans
removeHighlight();
$.each($tableElements, function (index, item) {
var $el = $(item);
if ($el.text().search(searchText) != -1 && !matched) {
//console.log("matched", $el, $el.html());
wrapContent(searchText.length, $el, $el.html());
//console.log(searchText, $el.text());
if (searchText == $el.text()) {
// found the entry
//console.log("matched");
matched = true;
}
}
});
};
$(function () {
//load table into object
var $tableRows = $('table tr');
var $tableElements = $tableRows.children();
//console.log($tableRows, $tableElements);
$('#search').on('keyup', function (e) {
var searchText = $(this).val();
if (searchText.length == 0) {
// catches false triggers with empty input (e.g. backspace delete or case lock switch would trigger the function)
removeHighlight(); // remove last remaining highlight
return;
}
highlightTextInTable($tableElements, searchText);
});
});
})();
.highlight {
background-color: #00FFFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search" />
<table>
<tr>
<td>TestX</td>
<td>Test1.2</td>
<td>Test1.3</td>
<td>Test1.4</td>
</tr>
<tr>
<td>Test2.1</td>
<td>TestY</td>
<td>Test2.3</td>
<td>Test2.4</td>
</tr>
<tr>
<td>Test3.1</td>
<td>TestY</td>
<td>Test3.3</td>
<td>Test3.4</td>
</tr>
</table>

Jquery Table Sum

I am trying to create rows every time I click the "+" button and sum every column. I can create columns.
But no rows.
This is my code:
$(document).ready(function () {
$("#tabla").click(function () {
$("tr").find("td:last").before('<td><input type="text" value="0"></td>');
$("tr:last").after('<td><input type="text" value="1"></td>');
$("input").each(function () {
$(this).keyup(function () {
newSum.call(this);
});
});
});
});
function newSum() {
var sum = 0;
var thisRow = $(this).closest('tr');
var total = 0;
$(thisRow).find("td:not(.total) input").each(function () {
sum += parseInt(this.value);
});
$(thisRow).find(".total").html(sum);
$('.total').each(function () {
total += parseInt($(this).html());
});
}
http://jsfiddle.net/YQ7LQ/
Thanks in advance.
Added rows and columns sum called on $(document).on('keyup','input',newSum);
Example
I finally resolved the problem.
Here's the code:
//Sum the Rows.
$('#sum_table tr:not(.totalCol) input:text').bind('keyup change', function() {
var $table = $(this).closest('table');
var total = 0;
var thisNumber = $(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
total += parseInt(this.value);
});
$table.find('.totalCol td:nth-child('+thisNumber+')').html(total);
});
Here is the full code:
DEMO

JQuery add/remove column/row dynamically

I'm trying to remove the columns that I created dynamically.
The link to remove a column works only on the first column.
When i press the link on the second column nothing is happen, but should show a message.
What's wrong?
Code :
$(document).ready(function(){
function deleteCol(currentNode){$(currentNode).remove();}
function deleteRow(currentNode){$(currentNode).parent().parent().remove();}
$('.AddColBtn').click(function(){
var colLength = $('tr.header th.col').length+1;
var rowLength = $('.row').length;
var vAddColc = $('.col').clone().html();
var vAddColr = vAddColc.replace("Col 1","Col "+colLength);
var vAddCol = '<th class="col">'+vAddColr+'</input></th>';
var vAddCell = '<td class="href" onclick="document.location.href="#11">Cell '+colLength+'</td>';
$('.ColAdd').before(vAddCol);
$('.RowDel').before(vAddCell);
});
$('.AddNewRow').click(function(){
var clonedRow = $('.row').clone().html();
var rowLength = $('.row').length+1;
var n = clonedRow.replace("Row 1","Row "+rowLength);
var appendRow = '<tr class = "row">' + n + '</tr>';
$('#myPureTable tr:last').after(appendRow);
});
$("a.delCol").click(function(event) {
event.preventDefault();
var colCnt = $('tr.header th.col').length;
alert(colCnt);
//var current_cell = $(this).closest("td");
//var nb_columns = current_cell.closest('table').find('tr:eq(1) td').length+1;
//var column_to_delete = current_cell.prevAll("td").length+1;
//if (colCnt>1){deleteCol('table tr td:nth-child('+(nb_columns+'n-'+(nb_columns-column_to_delete))+')');}
//$('table tr td:nth-child('+(nb_columns+'n-'+(nb_columns-column_to_delete))+')').remove();
});
$('.RowDelete').live('click',function(){
var rowLength = $('.row').length;
if(rowLength > 1){deleteRow(this);}
else{$('.employmentHistoryForm tr:last').after(appendRow);
deleteRow(this);}
});
});
Fiddle
That's because you don't take into account the fact you're not binding to dynamically created elements.
Change
$("a.delCol").click(function(event) {
to
$(document).on('click', "a.delCol", function(event) {

Categories