Javascript to add values of a table - javascript

my HTML code looks like this
<TR Row="1" CLASS="ThemeAlignCenter">
<TD id="wrdActive_Row1" style="width: 50px"
CLASS="rdThemeDataTableCell"><SPAN id="lblactive_Row1">6</SPAN></TD>
... more rows
I want to put a javascript at the end of the page to add all of the the values of lblactive_row1 when ever it appears in the page (in this example the number 6)
Edit: more source
<TABLE style="" border="0" CLASS="rdThemeDataTable" id="dtWardData"
cellspacing="0">
<COL id="wrdActive"></COL>
<COL id="wrdOccupied"></COL>
<TR Row="1" CLASS="ThemeAlignCenter">
<TD id="wrdActive_Row1" style="width: 50px"
CLASS="rdThemeDataTableCell"><SPAN id="lblactive_Row1">4</SPAN></TD>
<TD id="wrdOccupied_Row1" style="width: 50px"
CLASS="rdThemeDataTableCell"><SPAN id="lblOccupied_Row1">4</SPAN></TD>
</TR>
</TABLE>
<TABLE style="" border="0" CLASS="rdThemeDataTable" id="dtWardData"
cellspacing="0">
<COL id="wrdActive"></COL>
<COL id="wrdOccupied"></COL>
<TD id="wrdActive_Row1" style="width: 50px"
CLASS="rdThemeDataTableCell"><SPAN id="lblactive_Row1">6</SPAN></TD>
<TD id="wrdOccupied_Row1" style="width: 50px"
CLASS="rdThemeDataTableCell"><SPAN id="lblOccupied_Row1">2</SPAN></TD>
</TR>
</TABLE>
Repeat...
it goes on like that for another 10 or so tables, all in the same source. editting the html is out of the question because its generated by a third party tool. all i can is add a little script at the end

Depending on whether you're using jQuery or not, you might have to modify your HTML to make it easier to pick out the elements you need.
With jQuery you should be able to do something like this:
var total = 0;
$('table tr.ThemeAlignCenter > td.rdThemeDataTableCell > span').each(function(i) {
total += parseInt($(this).text());
});
Without jQuery, assuming your <table> has an id of data, something along these lines should help:
var tbl = document.getElementById('data');
var cells = tbl.getElementsByTagName('td');
var total = 0;
for (var i = 0, limit = cells.length; i < limit; i++) {
var td = cells[i];
if (td.className === 'rdThemeDataTableCell') {
var elem = td.getElementsByTagName('span')[0];
total += parseInt(elem.innerHTML);
}
}
EDIT: refactored the code so it can be applied to each table (should hopefully work if the table id attributes can't be amended and have to remain identical):
function sumTable(tbl) {
var cells = tbl.getElementsByTagName('td');
var total = 0;
for (var i = 0, limit = cells.length; i < limit; i++) {
var td = cells[i];
if (td.className === 'rdThemeDataTableCell') {
var elem = td.getElementsByTagName('span')[0];
total += parseInt(elem.innerHTML);
}
}
return total;
}
var tables = document.getElementsByTagName('table');
var results = [];
for (var i = 0, limit = tables.length; i < limit; i++) {
var total = sumTable(tables[i]);
results.push(total);
}

Something like this might work:
function totalRows() {
var total = 0;
var spans = document.getElementsByTagName('span');
for(var i=0; i<spans.length; i++) {
if(spans[i].getAttribute('id') === 'lblactive_Row1') {
total += parseInt( spans[i].innerHTML, 10);
}
}
return total;
}
attach totalRows() to an eventHandler

Related

Why isn't the JQuery script removing table rows

I'm trying my hand at web development and one of my early projects is to create a grid that is mutable in size and responds to mouse events.
For some reason (I'm sure there is a good one), my function to change the grid size doesn't always remove all of the necessary rows.
Ex. When changing the grid size from 10 to 4, or 6 to 2, there are additional rows that are not removed
CODE PEN
HTML
<!DOCTYPE html>
<html>
<head>
<title>My Grid</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id='container'>
<div id='userSettings'>
<h1>Welcome to "My Grid"</h1>
<form>
<input id='gridSizeValue' type='text' name="gridSize">
<input id='button' type='button' value="Change Grid Size">
</form>
</div>
<table class='mainTable' style="border-color: black; border-top-width: 5px;">
<tr class="tableRow">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
</tr>
<tr class="tableRow">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
</tr>
<tr class="tableRow">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
</tr>
<tr class="tableRow">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
</tr>
</table>
</div>
JavaScript
$(document).ready(function(){
$('#button').click(function(){
var gridSize = document.getElementById('gridSizeValue').value;
var amountOfTableRows = document.getElementsByClassName('tableRow').length;
setTableRows(amountOfTableRows, gridSize);
});
styleTable();
});
function setTableRows(currentAmountOfRows, newGridSize) {
// Check if the number of rows is less than or greater than current amount of rows
// either add or subtract rows
// loop through rows and either add or subtract columns
if (newGridSize > currentAmountOfRows) {
var rowsToAdd = newGridSize - currentAmountOfRows;
for (var i = 0; i < rowsToAdd; i++) {
$('.mainTable').append("<tr class=\"tableRow\"></tr>");
}
newAmountOfRows = document.getElementsByClassName('tableRow');
for (var i = 0; i < newAmountOfRows.length; i++) {
currentAmountOfColumnsInRow = newAmountOfRows[i].getElementsByClassName('tableColumn').length;
columnsToAdd = newGridSize - currentAmountOfColumnsInRow;
// console.log("Need to add " + columnsToAdd + "columns");
for (var j = 0; j < columnsToAdd; j++) {
$('.tableRow:nth-child(' + (i+1) +')').append("<td class=\"tableColumn\">");
}
}
}
else if (newGridSize < currentAmountOfRows){
var rowsToSubtract = currentAmountOfRows - newGridSize;
for (var i = 0; i < rowsToSubtract; i++) {
$('.tableRow:nth-child(' + (i+1) +')').remove();
}
newAmountOfRows = document.getElementsByClassName('tableRow');
for (var i = 0; i < newAmountOfRows.length; i++) {
currentAmountOfColumnsInRow = newAmountOfRows[i].getElementsByClassName('tableColumn').length;
columnsToSubtract = currentAmountOfColumnsInRow - newGridSize;
// console.log("There are " + currentAmountOfColumnsInRow + " columns in row" + (i+1));
for (var j = 0; j < columnsToSubtract; j++) {
$('.tableColumn:nth-child(' + (i+1) +')').remove();
}
}
}
styleTable();
}
function styleTable(){
$('td').mouseenter(function(){
$(this).css("background-color","white");
});
$('td').mouseleave(function(){
$(this).css("background-color","black");
});
//Option 1: set height and width of each "cell" to the total height of table / cound of rows
// rowHeight = $('td').eq(0).height();
tableHeight = 400;
// alert("The Table Height is" + tableHeight);
numberOfRows = document.getElementsByClassName('tableRow').length;
// alert("rows " + numberOfRows);
dynamicCellHeight = (tableHeight / numberOfRows);
// alert("The Cell Height is " + dynamicCellHeight);
cellHeightInt= Number(dynamicCellHeight);
$('td').height(cellHeightInt);
$('td').width(cellHeightInt);
}
When you already have 6 rows and change the size 2, your code will call pass through the else statement, where you do :
for (var i = 0; i < rowsToSubtract; i++) {
$('.tableRow:nth-child(' + (i+1) +')').remove();
}
You are subtracting 4 rows, so actually the code is executing:
$('.tableRow:nth-child(1)').remove();
$('.tableRow:nth-child(2)').remove();
$('.tableRow:nth-child(3)').remove();
// at this point your table has 3 rows
$('.tableRow:nth-child(4)').remove();
So at the last line, you are trying to remove the fourth line of a table which has 3 rows ... so nothing happens.
You could invert the for loop looping backwards from rowsToSubtract to 0, that would solve your problem. But there are better ways to do this...
Just explaining why it's going wrong here :)
(Concurrent issue?)
for (var i = rowsToSubtract; i > 0; i--) {
$('.tableRow:nth-child(' + (i) +')').remove();
}
When rows are being subtracted from 8 to 2 (by 6), starting from removing 5th row, you can't do remove since it does not exist.
And yep, the code to remove columns for each row should also be fixed like aforementioned:
for (var j = columnsToSubtract; j > 0; j--) {
$('.tableColumn:nth-child(' + (i) +')').remove();
}
Thank you both very much for your help, it makes sense that what I was was trying to remove items that the code has no reference to and therefor does nothing.
I rewrote the code in a much simpler function to simply redraw the table in a much more concise way.
function drawNewTable(newGridSize){
$('.mainTable').remove();
// Draw New Grid -> Add Table -> Add Rows -> Add Column
$('.tableDiv').append("<table class='mainTable'>")
for(var i = 0; i < newGridSize; i++){
$('.mainTable').append("<tr class='tableRow'>");
for(var j = 0; j < newGridSize; j++){
$('.tableRow:nth-child(' + (i+1) +')').append("<td class=\"tableColumn\">");
}
$('.mainTable').append("</tr>");
}
$('.tableDiv').append("</table>");
styleTable();
}

Select all button for selecting td tags

I have a table with each tr having class="ass testPageRow" I want to be able to all selected the td tags. I currently have some code that allows me to select the td individually. I am trying to implement a select all button.
var testPagesList = document.getElementsByClassName("testPageRow");
for (var i = 0; i < testPagesList.length; i++) {
var testPageItems = testPagesList[i].getElementsByTagName("td");
for (var j = 0; j < testPageItems.length; j++) {
testPageItems[j].onclick = function(event) {
if (this.className == "selected") {
this.className = "unselected";
} else {
this.className = "selected";
}
};
}
}
The format of my html
<table class="table">
<tbody>
<tr class="ass testPageRow">
<td id="tp1">1</td>
<td id="tp4">4</td>
<td id="tp5">5</td>
</tr>
<tr class="ass testPageRow">
<td id="tp12">12</td>
<td id="tp13">13</td>
<td id="tp14">14</td>
</tr>
<tr class="ass testPageRow">
<td id="tp14TTU">14TTU</td>
<td id="tp15">15</td>
<td id="tp16">16</td>
</tr>
<tr class="ass testPageRow">
<td id="tp18">18</td>
<td id="tp20">20</td>
<td id="tp21">21</td>
</tr>
</tbody>
</table>
Here is my current javascript code to select the tags. When I click the button, nothing happens. I'm not sure why. My logic was to iterate through all the objects and change the className to selected as I did in my previous code.
function selectAllTestPages() {
var selectAllTP = document.getElementById("selectAllTestPages");
selectAllTP.onclick = function(event) {
for (var i = 0; i < testPagesList.length; i++) {
var testPageTDTags = testPagesList[i].getElementsByTagName("td");
for (var td in testPageTDTags) {
td.className = "selected";
}
}
};
}
Button click:
<div class="center">
<button id="selectAllTestPages">Select All</button>
</div>
Perhaps try something like this?
Array.prototype.slice.call(document.querySelectorAll('.testPageRow td')).forEach(function(e) {
e.className = 'selected';
});
Demo: http://jsfiddle.net/62d4La7w/
You should really separate the function logic from the event listener logic.
The part of your code that was causing the functionality to break was the for in loop that you run on the testPageTDTags variable. You should have been using a regular loop with a counter.
Here's a new version of your code that will do what you are looking for:
// Logic to change all tds classes to 'selected'
function selectAllTestPages() {
var testPagesList = document.getElementsByClassName("testPageRow");
for (var i = 0; i < testPagesList.length; i++) {
var testPageTDTags = testPagesList[i].getElementsByTagName("td");
for (var j = 0; j < testPageTDTags.length; j++) {
testPageTDTags[j].className = "selected";
}
}
}
// Event listener that listens for button click
var button = document.getElementById('selectAllTestPages');
button.addEventListener('click', function(){
selectAllTestPages();
});
Here's a working example on jsfiddle

How do I select rows that correspond to a rowspan?

I have a dynamically generated table that I am trying to change the background color of certain rows in. Sometimes there are rows with rowspans and I cant figure out how to get all of the rows that correspond to the one "row." I've googled my brains out and found this jsfiddle which is pretty close to what i need (in a logic sense)
http://jsfiddle.net/DamianS1987/G2trb/
basically i have something like this:
and I want to be able to highlight full rows at a time like this:
but the only highlighting i can achieve on rowspan rows is this:
Here is my code (different from jsfiddle but essentially same logic)
CSS:
.highlightedClass{
background-color: #AEAF93;
}
HTML:
<table border="1" class="altTable">
<th>ID</th>
<th>NAME</th>
<th>Miles</th>
<th>WORK</th>
<tbody>
<tr>
<td class="td_id">999B</td>
<td class="td_name ">John</td>
<td class="td_cumMiles">702.4</td>
<td class="td_workEvent">Y</td>
</tr><tr>
<td class="td_id" rowspan="2">111A</td>
<td class="td_name">Tom</td>
<td class="td_cumMiles">446.5</td>
<td class="td_workEvent">Y</td>
</tr><tr>
<td class="td_name">Becky</td>
<td class="td_cumMiles">446.5</td>
<td class="td_workEvent">A</td>
</tr>
</tbody>
JAVASCRIPT:
for(var j=0; j < inspection.length; j++){
var $tr = $('<tr></tr>');
var $td_id = $('<td></td>').addClass('td_id').html(inspection.id);
$tr.append($td_id);
$table.append($tr);
$.each(inspection[i], function(index, value){
var $td_name, $td_miles,$td_workEvent;
if(index > 0){
var $2nd_tr = $('<tr></tr>');
$td_name = $('<td></td>').addClass('td_name').html(value.stationSt);
$td_miles = $('<td></td>').addClass('td_miles').html(value.miles);
$td_workEvent = $('<td></td>').addClass('td_workEvent').html(value.code);
$2nd_tr.append($td_name);
$2nd_tr.append($td_miles);
$2nd_tr.append($td_workEvent);
$table.append($2nd_tr);
$td_id.attr('rowSpan',index+1);
if($td_id.text() === content().id){
$2nd_tr.addClass("highlightedClass");
}else{
if($2nd_tr.hasClass("highlightedClass")){
$2nd_tr.removeClass('highlightedClass');
}
}
$('#workevent').on('click', function(){
$tr.removeClass('highlightedClass');
});
}else{
$td_name = $('<td></td>').addClass('td_name').html(value.stationSt);
$td_miles = $('<td></td>').addClass('td_miles').html(value.miles);
$td_workEvent = $('<td></td>').addClass('td_workEvent').html(value.code);
$tr.append($td_name);
$tr.append($td_miles);
$tr.append($td_workEvent);
$table.append($tr);
if($td_id.text() === content().id){
$tr.addClass("highlightedClass");
}else{
if($tr.hasClass("highlightedClass")){
$tr.removeClass('highlightedClass');
}
}
$('#workevent').on('click', function(){
$tr.removeClass('highlightedClass');
});
}
});
You need to look for any rowspan= attribute in the selected tds and if present, select the subsequent row(s) as well. This example should support any rowspan value (it appends subsequent rows based on the rowspan count):
Final version: JSFiddle: http://jsfiddle.net/TrueBlueAussie/G2trb/22/
$('td').bind('click', function () {
var $row = $(this).closest('tr');
// What row index is the clicked row?
var row = $row.index(); // Subtract heading row
// Does the clicked row overlap anything following?
var rowspan = ~~$row.find('td[rowspan]').attr('rowspan') || 0;
// Get all rows except the heading, up to the last overlapped row
var $rows = $row.parent().children().slice(1, row + rowspan);
row--; // Subtract the heading row we excluded
// Now see if any preceding rows overlap the clicked row
$rows.each(function (i) {
var $tr = $(this);
// Only check first rowspan of a row
var rowspan = ~~$tr.find('td[rowspan]').attr('rowspan') || 0;
// If the rowspan is before the clicked row but overlaps it
// Or it is a row we included after the selection
if ((i < row && ((rowspan + i) > row)) || i > row) {
$row = $row.add($tr);
}
});
$row.toggleClass('green');
});
First attempt JSFiddle: http://jsfiddle.net/TrueBlueAussie/G2trb/18/
$('td').bind('click', function () {
var $td = $(this);
var $row = $td.closest('tr');
var $tds = $row.find('td');
$tds.each(function(){
var rowspan = ~~$(this).attr('rowspan');
while (--rowspan > 0){
$row = $row.add($row.next());
}
});
$row.toggleClass('green');
});
It needs to be tweaked for the child row that sits under a previous rowspan, but am working on that too.
Notes:
~~ is a shortcut to convert a string to an integer.
the || 0 converts undefined values to 0.
$row = $row.add($tr) is appending row elements to a jQuery collection/object.
In fixing my issue (going off what TrueBlueAussie gave me) I came up with the following solution.
CSS:
.highlightedClass{
background-color: #AEAF93;
}
HTML:
<table border="1" class="altTable">
<th>ID</th>
<th>NAME</th>
<th>Miles</th>
<th>WORK</th>
<tbody>
<tr>
<td class="td_id">999B</td>
<td class="td_name ">John</td>
<td class="td_cumMiles">702.4</td>
<td class="td_workEvent">Y</td>
</tr><tr>
<td class="td_id" rowspan="2">111A</td>
<td class="td_name">Tom</td>
<td class="td_cumMiles">446.5</td>
<td class="td_workEvent">Y</td>
</tr><tr>
<td class="td_name">Becky</td>
<td class="td_cumMiles">446.5</td>
<td class="td_workEvent">A</td>
</tr>
</tbody>
JAVASCRIPT:
for(var j=0; j < inspection.length; j++){
var $tr = $('<tr></tr>');
var $td_id = $('<td></td>').addClass('td_id').html(inspection.id);
$tr.append($td_id);
$table.append($tr);
$.each(inspection[i], function(index, value){
var $td_name, $td_miles,$td_workEvent;
if(index > 0){
var $2nd_tr = $('<tr></tr>');
$td_name = $('<td></td>').addClass('td_name').html(value.stationSt);
$td_miles = $('<td></td>').addClass('td_miles').html(value.miles);
$td_workEvent = $('<td></td>').addClass('td_workEvent').html(value.code);
$2nd_tr.append($td_name);
$2nd_tr.append($td_miles);
$2nd_tr.append($td_workEvent);
$table.append($2nd_tr);
$td_id.attr('rowSpan',index+1);
if($td_id.text() === content().td_id){
$2nd_tr.addClass("highlightedClass");
}else{
if($2nd_tr.hasClass("highlightedClass")){
$2nd_tr.removeClass('highlightedClass');
}
}
$('#workevent').on('click', function(){
if($td_id.text() === content().td_id){
$2nd_tr.addClass("highlightedClass");
}else{
if($2nd_tr.hasClass("highlightedClass")){
$2nd_tr.removeClass("highlightedClass");
}
}
});
}else{
$td_name = $('<td></td>').addClass('td_name').html(value.stationSt);
$td_miles = $('<td></td>').addClass('td_miles').html(value.miles);
$td_workEvent = $('<td></td>').addClass('td_workEvent').html(value.code);
$tr.append($td_name);
$tr.append($td_miles);
$tr.append($td_workEvent);
$table.append($tr);
if($td_id.text() === content().id){
$tr.addClass("highlightedClass");
}else{
if($tr.hasClass("highlightedClass")){
$tr.removeClass('highlightedClass');
}
}
}
});
This was in a nested if statement. below like three if statements, i put this:
$('#workevent').on('click', function(){
var flag= false;
$('#altTable > tbody > tr').each(function() {
$td_id= $(this).find('.td_id');
if($td_id.text() === ''){
if(flag === true){
$(this).addClass("highlightedClass");
flag = true;
}
}else{
if(if($td_id.text() === content().idtd_id{){
if($(this).hasClass("highlightedClass")){
flag = true;
}else{
$(this).addClass("highlightedClass");
flag = true;
}
}else{
flag = false;
if($(this).hasClass("highlightedClass")){
$(this).removeClass("highlightedClass");
}
}
}
});
});
This is what worked for me. I selected TrueBlueAussie's answer because it helped get me my specific answer. Hopefully both answers can help someone else in the future.

Insert multiple rows and columns to a table in html dynamically using javascript code

I am trying to insert multiple rows and columns to create a table in html dynamically by selecting the number of rows and columns in dropdown list using javascript code like in MS Word.
For example if I select number of rows as 5 and number of columns as 5 from the dropdown list of numbers. 5 rows and 5 columns should get displayed.
My question is how can I add multiple rows and columns dynamically to create a table by selecting the number of rows and columns from the drop down list.
Since, <table> element is the one of the most complex structures in HTML, HTML DOM provide new interface HTMLTableElement with special properties and methods for manipulating the layout and presentation of tables in an HTML document.
So, if you want to accomplish expected result using DOM standards you can use something like this:
Demo old
Demo new
HTML:
<ul>
<li>
<label for="column">Add a Column</label>
<input type="number" id="column" />
</li>
<li>
<label for="row">Add a Row</label>
<input type="number" id="row" />
</li>
<li>
<input type="button" value="Generate" id="btnGen" />
<input type="button" value="Copy to Clipboard" id="copy" />
</li>
</ul>
<div id="wrap"></div>
JS new:
JavaScript was improved.
(function (window, document, undefined) {
"use strict";
var wrap = document.getElementById("wrap"),
setColumn = document.getElementById("column"),
setRow = document.getElementById("row"),
btnGen = document.getElementById("btnGen"),
btnCopy = document.getElementById("btnCopy");
btnGen.addEventListener("click", generateTable);
btnCopy.addEventListener("click", copyTo);
function generateTable(e) {
var newTable = document.createElement("table"),
tBody = newTable.createTBody(),
nOfColumns = parseInt(setColumn.value, 10),
nOfRows = parseInt(setRow.value, 10),
row = generateRow(nOfColumns);
newTable.createCaption().appendChild(document.createTextNode("Generated Table"));
for (var i = 0; i < nOfRows; i++) {
tBody.appendChild(row.cloneNode(true));
}
(wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.children[0]);
}
function generateRow(n) {
var row = document.createElement("tr"),
text = document.createTextNode("cell");
for (var i = 0; i < n; i++) {
row.insertCell().appendChild(text.cloneNode(true));
}
return row.cloneNode(true);
}
function copyTo(e) {
prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
}
}(window, window.document));
JS old:
(function () {
"use strict";
var wrap = document.getElementById("wrap"),
setColumn = document.getElementById("column"),
setRow = document.getElementById("row"),
btnGen = document.getElementById("btnGen"),
copy = document.getElementById("copy"),
nOfColumns = -1,
nOfRows = -1;
btnGen.addEventListener("click", generateTable);
copy.addEventListener("click", copyTo);
function generateTable(e) {
var newTable = document.createElement("table"),
caption = newTable.createCaption(),
//tHead = newTable.createTHead(),
//tFoot = newTable.createTFoot(),
tBody = newTable.createTBody();
nOfColumns = parseInt(setColumn.value, 10);
nOfRows = parseInt(setRow.value, 10);
caption.appendChild(document.createTextNode("Generated Table"));
// appendRows(tHead, 1);
// appendRows(tFoot, 1);
appendRows(tBody);
(wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.firstElementChild);
}
function appendColumns(tElement, count) {
var cell = null,
indexOfRow = [].indexOf.call(tElement.parentNode.rows, tElement) + 1,
indexOfColumn = -1;
count = count || nOfColumns;
for (var i = 0; i < count; i++) {
cell = tElement.insertCell(i);
indexOfColumn = [].indexOf.call(tElement.cells, cell) + 1;
cell.appendChild(document.createTextNode("Cell " + indexOfColumn + "," + indexOfRow));
}
}
function appendRows(tElement, count) {
var row = null;
count = count || nOfRows;
for (var i = 0; i < count; i++) {
row = tElement.insertRow(i);
appendColumns(row);
}
}
function copyTo(e) {
prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
}
}());
If you want to copy generated result to clipboard you can look at answer of Jarek Milewski - How to copy to the clipboard in JavaScript?
You can use this function to generate dynamic table with no of rows and cols you want:
function createTable() {
var a, b, tableEle, rowEle, colEle;
var myTableDiv = document.getElementById("DynamicTable");
a = document.getElementById('txtRows').value; //No of rows you want
b = document.getElementById('txtColumns').value; //No of column you want
if (a == "" || b == "") {
alert("Please enter some numeric value");
} else {
tableEle = document.createElement('table');
for (var i = 0; i < a; i++) {
rowEle = document.createElement('tr');
for (var j = 0; j < b; j++) {
colEle = document.createElement('td');
rowEle.appendChild(colEle);
}
tableEle.appendChild(rowEle);
}
$(myTableDiv).html(tableEle);
}
}
Try something like this:
var
tds = '<td>Data'.repeat(col_cnt),
trs = ('<tr>'+tds).repeat(row_cnt),
table = '<table>' + trs + '</table>;
Then place the table in your container:
document.getElementById('tablePreviewArea').innerHTML = table;
Or with JQuery:
$('#tablePreviewArea').html(table);
Here is the JSFiddle using native js.
Here is the JSFiddle using jQuery.
About the string repeat function
I got the repeat function from here:
String.prototype.repeat = function( num )
{
return new Array( num + 1 ).join( this );
}
I had one sample code...try this and modify it according to your requirement. May it helps you out.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<style type="text/css">
#mytab td{
width:100px;
height:20px;
background:#cccccc;
}
</style>
<script type="text/javascript">
function addRow(){
var root=document.getElementById('mytab').getElementsByTagName('tbody')[0];
var rows=root.getElementsByTagName('tr');
var clone=cloneEl(rows[rows.length-1]);
root.appendChild(clone);
}
function addColumn(){
var rows=document.getElementById('mytab').getElementsByTagName('tr'), i=0, r, c, clone;
while(r=rows[i++]){
c=r.getElementsByTagName('td');
clone=cloneEl(c[c.length-1]);
c[0].parentNode.appendChild(clone);
}
}
function cloneEl(el){
var clo=el.cloneNode(true);
return clo;
}
</script>
</head>
<body>
<form action="">
<input type="button" value="Add a Row" onclick="addRow()">
<input type="button" value="Add a Column" onclick="addColumn()">
</form>
<br>
<table id="mytab" border="1" cellspacing="0" cellpadding="0">
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
Instead of button , you can use select menu and pass the value to variable. It will create row ,column as per the value.

How to check for duplicate row using javascript

how do I check for duplicate row in a table using javascript? The following is part of my code:
<table id="t1">
<tr>
<td>Text A</td>
<td>Text B</td>
<td>Cbx A</td>
</tr>
<% int count1 = -1;
for(int i=0; i<3; i++) { %>
<tr>
<td><input type="text" id="textA<%=i%>"></td>
<td><input type="text" id="textB<%=i%>"></td>
<td><select name="cbx_A<%=i%>">
<option value="A">Option1</option>
<option value="B">Option2</option>
</select>
</td
</tr>
<%count1 =i;
}%>
<tr>
<td><input type="button" onclick="check(<%=count1%>)" value="Check"></td>
</tr>
</table>
So based on this code, I will have 3 rows of text A,textB and cbxA. With that, how do I check whether user input the same values for 2 of the rows or all three rows?
I tried using servlet but theres too much work involve. So yeah is there a way to do this using java script instead?
Thanks in advance for any possible help.
Using this code it will check for duplication in one table column
then take all rows of table that are duplicated and put their ids in array
so you will get an array of rows id
but ur table has to have an id for each row
var columnNumber = 1;
var table = document.getElementById('t1');
var rowLength = table.rows.length;
var arrReocrds = new Array();
var arrCount = 0;
var listCount = 0;
var arr = new Array();
$('#t1 td:nth-child(' + colNumber + ')').each(function () {
var recordValue = $(this).html().trim();
var flagFirstTime = true;
//loop through table to check redundant of current record value
for (var i = 1; i < rowLength; i += 1) {
{
var row = table.rows[i];
var recordId = //put here row.id or anything that you can put it in the list
var cell = row.cells[colNumber - 1];
var value = cell.innerText.trim();
if (value == recordValue) {
if (!arr.contains(value)) {
if (flagFirstTime != true) {
arrReocrds[arrCount] = recordId;
arrCount++;
}
else
flagFirstTime = false;
}
else
break;
}
}
}
//create list for items in column
//to be sure that the item that has been taken and checked never be checked again by their other redundant records
arr[listCount] = recordValue;
listCount++;
});

Categories

Resources