JavaScript Get data of a clicked row - javascript

Good Evening, i want to get all the data from the row that the user clicks on, so i tried this script, it gets the row id but it doesn't get the data exists in that row, i push every data in that row to an array for further uses:
function findRowNumber() {
var rowIdx;
var rowData = new Array();
var table = document.getElementById('product_table');
var rows = table.getElementsByTagName('tr');
var selectedRow;
var rowCellValue;
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
rowIdx = this.rowIndex;
selectedRow = rows[rowIdx];
for (j = 1; j < selectedRow.length; j++) { // it doesn't enter that loop
rowCellValue = selectedRow.cells[j].value;
rowData.push(rowCellValue);
alert("Value " + rowCellValue);
}
}
}
}

selectedRow is populated after you click the row, while you are trying to loop trough it after binding the click handler, but before the actual click. You have to move that code in the click handler

If the data in the cells is text,
it may be simpler to retrieve with textContent(or innerText).
<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title> Small Test Page</title>
<style>
table{border:3px ridge #c0c0c0;border-collapse:collapse;}
th, td{border:1px solid black}
</style>
<script>
function findRowNumber(){
var rowIdx;
var rowData= [];
var table= document.getElementById('product_table');
var rows= table.getElementsByTagName('tr');
var selectedRow;
var rowCellValue;
for(i= 0;i<rows.length;i++){
rows[i].onclick= function(){
rowIdx= this.rowIndex;
selectedRow= this.cells;
for(j= 0;j<selectedRow.length;j++){
rowCellValue= selectedRow[j].textContent ||
selectedRow[j].innerText;
rowData.push('cell '+j+': '+rowCellValue);
}
alert("Row #" +rowIdx+'. '+ rowData);
}
}
}
</script>
</head>
<body>
<h1> Retrieve Row Data</h1>
<p> <button type= "button" id= "tableSwapBtn" onclick= "findRowNumber()">
Click to initialize</button> </p>
<table id="product_table" style="width:300px">
<tbody>
<tr> <td> a</td> <td> 1</td> </tr>
<tr> <td> b</td> <td> 2</td> </tr>
<tr> <td> c</td> <td> 3</td> </tr>
<tr> <td> d</td> <td> 4</td> </tr>
<tr> <td> e</td> <td> 5</td> </tr>
<tr> <td> f</td> <td> 6</td> </tr>
<tr> <td> g</td> <td> 7</td> </tr>
</tbody>
</table>
</body>
</html>

Related

Toggle elements from classes with JS

I would like to show more information when someone click on show more buttons. The complication is that there are several buttons and informations to toggle with same className.
What am I doing wrong??
var element = document.querySelectorAll("btn");
for (var i = 0; i < button_length ; i++) {
element[i].addEventListener("click", function() {
alert("Button Clicked " + i);
element[i].classList.toggle("extrainfo");
};
}
td{border:solid 1px black;}
.btn, #btn_id{color:blue; text-decoration:underline; cursor:pointer;}
.extrainfo{
display:none
}
<table>
<tbody>
<tr class="info_group">
<td>Title 1</td>
<td class="btn">show more</td>
</tr>
<tr>
<td class="extrainfo" colspan="2">More info 1</td>
</tr>
</tbody>
<tbody>
<tr class="info_group">
<td>Title 2</td>
<td class="btn">show more</td>
</tr>
<tr>
<td class="extrainfo" colspan="2">More info 2</td>
</tr>
</tbody>
<tbody>
<tr class="info_group">
<td>Title 3</td>
<td class="btn">show more</td>
</tr>
<tr>
<td class="extrainfo" colspan="2">More info 3</td>
</tr>
</tbody>
</table>
to work you javaScript
var element = document.querySelectorAll("btn"); // need to be (".btn")
// you want it to be i < element.length; ? or there's a variable called button_length?
for (var i = 0; i < button_length ; i++) {
element[i].addEventListener("click", function() {
alert("Button Clicked " + i);
element[i].classList.toggle("extrainfo");
}; // missing a Parenthesis need to be this }); not this };
}
I'm still not sure about the functionality, but see the code below if that's what you're looking for.
var element = document.querySelectorAll(".btn");
var extraInfo = document.querySelectorAll(".extrainfo");
for (let i = 0; i < element.length; i++) {
element[i].addEventListener("click" , function() {
extraInfo[i].classList.toggle("extrainfo");
});
}
hereJSFiddle you can play around with the code

change attribute of appended element

for (var i = 0; i < 10; i++) {
var tr = $("<tr></tr>")
tr.append("<td>1</td>");
tr.append("<td>2</td>");
$("table tbody").append(tr)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody></tbody>
</table>
How Can I append rows and then dynamically change the rowspan of every second row. What I want to happend is it will look like below:
<table border='1'>
<tbody>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
</tbody>
</table>
I tried using index but it is not adding the rowspan
Any help is appreciated.
FYI : What I want to happened is append first then change the row span after the row is appended
Just added mod (%)
for (var i = 0; i < 10; i++) {
var tr = $("<tr></tr>");
if(i%2===0){
tr.append("<td rowspan='2'>1</td>");
}
tr.append("<td>2</td>");
$("table tbody").append(tr)
}
td, th {
border: 1px solid #ddd;
padding: 8px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table>
<tbody></tbody>
</table>
</body>
</html>
I hope I achieve what you need.
I base the result from your second snippet.
for (var i = 0; i < 10; i++) {
var tr = $("<tr></tr>")
tr.append("<td>1</td>");
tr.append("<td>2</td>");
$("table tbody").append(tr)
}
$('button').click(function(){
$('table tr:odd td:first-child').remove();
$('table tr:even td:first-child').attr('rowspan', 2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
<tbody></tbody>
</table>
<button>append</button>
try to use html string and then attach it to your element and make the rowspan dynamic for example :
var html_string = '<tr>'
for (var i = 0; i < 10; i++) {
html_string+= '<td rowspan="'+i+'">1</td>'
html_string += '<td>2</td>'
}
html_string +='</tr>'
$("table tbody").append(html_string)
Below code may help,
for (var i = 0; i < 10; i++) {
var tr = $("<tr></tr>");
tr.append("<td>1</td>");
tr.append("<td>2</td>");
$("table tbody").append(tr)
}
$('table tr:odd td:first-child').remove();
$('table tr:even td:first-child').attr('rowspan', 2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border='1'>
<tbody></tbody>
</table>

Hide rows in table B which already appear in table A

Using this code :
var table1 = $('#TableA').find('td:eq(1)').text();
var table2 = $("#TableB tr:gt(0)");
table2.each(function (i) {
var tds = $(this).children('td');
var type= +tds.eq(0).text();
var price = +tds.eq(1).text();
if (price == table1) {
var myTable = table2.filter(function () {
var tds = $(this).children('td');
})
myTable.add(this).hide()
}
})
My Html Page Structure
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table id="TableA">
<tr>
<th>Type</th>
<th>Price</th>
<th>Quantity</th>
<th>Ref No</th>
</tr>
<tr>
<td>Mouse</td>
<td>50</td>
<td>6</td>
<td>#101255</td>
</tr>
<tr>
<td>Speaker</td>
<td>300</td>
<td>6</td>
<td>#21165</td>
</tr>
</table>
<table id="TableB">
<tr>
<th>Type</th>
<th>Price</th>
<th>Quantity</th>
<th>Ref No</th>
</tr>
<tr>
<td>Mouse</td>
<td>50</td>
<td>6</td>
<td>#101255</td>
</tr>
<tr>
<td>Speaker</td>
<td>300</td>
<td>6</td>
<td>#21165</td>
</tr>
<tr>
<td>Keyboard</td>
<td>150</td>
<td>7</td>
<td>#31234</td>
</tr>
</table>
</body>
</html>
"The second table in the images is the Table B"
My Table B changes from this :
Before
To this : After
Now my problem is, only one row is hidden. The row, where "speaker" is, is still displayed. I know that I must use a loop for this, but I don't where to implement the loop and how. I'm a newbie programmer and I know that I need more practice. Please Help Thank you in advance
<script type="text/javascript">
$('body').click(function(e){
var table1_tr = $('#TableA').find('tr'); <!--get the rows of first table-->
var table2 = $("#TableB tr:gt(0)");
table1_tr.each(function(i,e){ <!-- loop through rows of first table -->
var table1 = $(e).find('td:eq(1)').text();
table2.each(function (i) {
var tds = $(this).children('td');
var type= +tds.eq(0).text();
var price = +tds.eq(1).text();
if (price == table1) {
var myTable = table2.filter(function () {
var tds = $(this).children('td');
})
myTable.add(this).hide()
}
});
})
});
</script>
you are checking the text of price in the first row of first table with td text of all the rows of second table
I modified script to loop through rows of first table and check them with all rows of second table
Hope this helps

Is it possible to find number of td's within table and then apply col width inside table tag by using Javascript?

Is it possible to add "col width" tag according to number of td tags, within Table tag. if there are 2 td's,then it should add 2 "col width". & if there are 3 then, 3 "col width". and so on.
<!DOCTYPE html>
<html>
<head>
<title>HTML colgroup Tag</title>
</head>
<body>
<p>This example shows a colgroup that has three columns of different widths:
</p>
<table border="1">
<tr>
<th>Heading</th>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</tr>
</table>
<table border="1">
<tr>
<td>col 1</td>
<td>col 2</td>
</tr>
</table>
</body>
</html>
Please can anyone help me,to add "col group" tag according to number of td.
Expected Output:-
<!DOCTYPE html>
<html>
<head>
<title>HTML colgroup Tag</title>
</head>
<body>
<p>This example shows a colgroup that has three columns of different widths:
</p>
<table border="1">
<colgroup>
<col width="50%"></col>
<col width="20%"></col>
<col width="30%"></col>
</colgroup>
<tr>
<th>Heading</th>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</tr>
</table>
<table border="1">
<colgroup>
<col width="50%"></col>
<col width="50%"></col>
</colgroup>
<tr>
<td>col 1</td>
<td>col 2</td>
</tr>
</table>
</body>
</html>
you need to first loop through the tables and get the td count for each table. and then create a colgroup based on the count of td's
something like this
var output = '';
$('table').each(function() {
var colCount = 0;
$(this).find('tr:nth-child(1) td').each(function() { // Get the count of table columns
if ($(this).attr('colspan')) { // if there is a <td colspan>
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
console.log($(this));
});
var colgroupList = '';
for (i = 0; i < colCount; i++) { // Add a <colgroup></colgroup> for each <td>
colgroupList += '<col width="50%"></col>';
console.log(colgroupList);
}
console.log('<colgroup>' + colgroupList + '</colgroup>');
$(this).find("tbody").prepend('<colgroup>' + colgroupList + '</colgroup>');
output += $(this).html();
});
here's a working JSFIDDLE for the same.
In jQuery you can count the number of tds in the table by:
var count = $('#tableId td').length();
You can add atrributes to a table by doing:
$('#tableId').attr('name', 'value');
jQuery('table').each(function(){
var t = jQuery(this);
var count = t.children('tr').eq(0).find('td').length;
var colgroup = jQuery('<colgroup/>', { 'span': count });
for(var i = 1; i <= count; i++){
colgroup.append('<col/>',{ 'width' : (100/count)+'%' };
}
t.prepend(colgroup);
});
Untested but should be a good starting point
Yes, you can use jQuery to make things easy.
Here is an example (I used the id "table1" in the table):
$(document).ready(function () {
var size = $("#table1 tr:first > td").length;
var tg = '<colgroup span="' + size + '">';
for(x=0; x<size; x++) {
tg += '<col></col>';
}
tg += '</colgroup>';
$(tg).insertBefore('#table1 > tbody > tr:first');
});
Hope it helps.

How to update the table when a certain row is deleted using Javascript

I want to update the index when the Rows are deleted in the Table.
For e.g. I delete row 1, then the rows 2 and 3 should become 1 and 2, so on.
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
Well you dont need to do anything! when ever a row is deleted from dom, automatically the row index is changed.
if you want to closely examine you can hook an mutationevent DOMNodeRemoved and see whats happening, or just keep a break point after delete and verify the row count and indexes.
Here is a complete jQuery solution:
Test it here. Just click on a row to delete it.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js""></script>
<script>
$(function () {
$('tr').click(function () {
$(this).remove()
recountRows();
});
var recountRows = function () {
var index = 1;
$('.index').each(function () {
$(this).html(index);
index++;
});
}
});
</script>
</head>
<body>
<table>
<tr>
<td class="index">1</td><td>table text</td>
</tr>
<tr>
<td class="index">2</td><td>table text</td>
</tr>
<tr>
<td class="index">3</td><td>table text</td>
</tr>
<tr>
<td class="index">4</td><td>table text</td>
</tr>
<tr>
<td class="index">5</td><td>table text</td>
</tr>
<tr>
<td class="index">6</td><td>table text</td>
</tr>
<tr>
<td class="index">7</td><td>table text</td>
</tr>
<tr>
<td class="index">8</td><td>table text</td>
</tr>
</table>
</body>
</html>

Categories