How to delete all columns of a row using Javascript - javascript

I have the following code to delete the columns of a table:
let xvm = document.getElementsByClassName("removedor");
let k = 0
let y = document.querySelectorAll('td')
let ya = document.querySelectorAll('td').length
let z = document.querySelectorAll('th')
let za = document.querySelectorAll('th').length
let restaurador = document.getElementsByClassName('restaurador');
for (let k = 0; k < za; k++) {
let xvm = document.getElementsByClassName("removedor");
let y = document.querySelectorAll('td')
let ya = document.querySelectorAll('td').length
let z = document.querySelectorAll('th')
let za = document.querySelectorAll('th').length
let restaurador = document.getElementsByClassName('restaurador');
document.getElementsByClassName("removedor")[k].addEventListener("click", function() {
z[k].style.display = "none";
y[k].style.display = "none";
})
}
The code works with only the first row when i click to delete the columns. I want it to delete the column that i clicked from all the rows from the table.

You can add a class to each delete button, then run a forEach loop over that nodelist and check for a click. When the click hits use the event.target and head up the nodelist to the nearest parent element to add a verification => e.target.closest('td') this will give you the table data element your button is residing within. Then you can insert a verification to make sure the user wishes to delete or not, getting the id of the row =>
td.insertAdjacentHTML('beforeend', ` <label class="checkLabel">Delete ${row}? <input type="checkbox" class="checkYes"></label>`);
A second event listener to check if the class we add into the DOM for the check is present in the DOM => checkYes.addEventListener('change', deleteRow); if this is not present we add the HTML that will delete the row.
checkYes.addEventListener('change', deleteRow);
The function to deleteRow:
function deleteRow(e){
e.target.closest('tr').remove();
}
I did not add a toggle for the delete button, but you could also add a toggle to the delete button that will hide the secondary verification if you hit the delete button again.
const del = document.querySelectorAll('.del');
function deleteRow(e) {
e.target.closest('tr').remove();
}
function checkDel(e) {
let td = e.target.closest('td');
let row = e.target.closest('tr').id;
if (!td.querySelector('.checkYes')) {
td.insertAdjacentHTML('beforeend', ` <label class="checkLabel">Delete ${row}? <input type="checkbox" class="checkYes"></label>`);
}
let checkYes = td.querySelector('.checkYes');
checkYes.addEventListener('change', deleteRow);
}
del.forEach(btn => {
btn.addEventListener('click', checkDel);
})
<table id="myTable">
<tr id="row_1">
<td>Row 1 Col 1</td>
<td>Row 1 Col 2</td>
<td>Row 1 Col 3</td>
<td>Row 1 Col 4</td>
<td><button class="del">Delete this row</button></td>
</tr>
<tr id="row_2">
<td>Row 2 Col 1</td>
<td>Row 2 Col 2</td>
<td>Row 2 Col 3</td>
<td>Row 2 Col 4</td>
<td><button class="del">Delete this row</button></td>
</tr>
<tr id="row_3">
<td>Row 3 Col 1</td>
<td>Row 3 Col 2</td>
<td>Row 3 Col 3</td>
<td>Row 3 Col 4</td>
<td><button class="del">Delete this row</button></td>
</tr>
</table>

Related

Vuejs - tr row not showing 100% when adding display block

In my VuewJS application, I want to be able to click a row and show/hide the row below. However, when I do that I get a weird bug were the row below only fills one column width.
Here is my table structure:
NOTE: This table is generated dynamically.
The top row with 4 columns has an attribute of id and the long row that fills up 4 columns has a a data attribute data-body-id.
<tr v-bind:key="data.id" v-bind:id="index" v-on:click="rowClick(index)">
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
<td>Col 4</td>
</tr>
<tr v-bind:key="data.id" v-bind:data-body-id="index">
<td colspan="4">Col 5 (This is a really long 4 colspan row ..............)</td>
</tr>
which computes as:
<tr data-v-1a25d82d="" id="0">
<td data-v-1a25d82d="">Col 1</td>
<td data-v-1a25d82d="">Col 2</td>
<td data-v-1a25d82d="">Col 3</td>
<td data-v-1a25d82d="">Col 4</td>
</tr>
<tr data-v-1a25d82d="" data-body-id="0">
<td data-v-1a25d82d="" colspan="4">Col 5 (This is a really long 4 colspan row ..............)</td>
</tr>
in my rowClick(index) method I have:
methods: {
rowClick(id) {
var dataId = "data-body-id='" + id + "'";
var row = document.querySelector('[' + dataId + ']');
row.style.display = 'block';
}
}
When I click a row, the row below is visible but it shows like so:
If I use the developer inspector and find the attribute and uncheck the display: none; that is set in the CSS initially to hide the row it shows perfectly.
What is going on and how do I fix it?
When trying to show dynamic table rows that are hidden please use:
display: 'table-row',
so in your case:
row.style.display = 'table-row';

create a .row.cells line for length of <tr>

Hello I want to create a script that takes the amount of (tr) it finds then creates these 3 lines of code but changes the number in them based on the number it gets of (tr) here is an example:
I have a line of code that counts the table rows in the table (after I press a button) minus the table header (th):
var rowCount = $('#items-table tr').length - 1;
what I want to do is say for example the number I get is 3, I want to duplicate these 3 lines of code and change the variable and the number inside them.
Here are the 3 lines of code I want to duplicate:
table = document.getElementById("items-table");
var cell1 = table.rows[1].cells[0].innerHTML;
var cell2 = table.rows[1].cells[1].innerHTML;
var cell3 = table.rows[1].cells[2].innerHTML;
what I want to change is the var so I can define it later so if I got 3 this is what I would want the output to be:
var cell1 = table.rows[1].cells[0].innerHTML;
var cell2 = table.rows[1].cells[1].innerHTML;
var cell3 = table.rows[1].cells[2].innerHTML;
var cell4 = table.rows[2].cells[0].innerHTML;
var cell5 = table.rows[2].cells[1].innerHTML;
var cell6 = table.rows[2].cells[2].innerHTML;
var cell7 = table.rows[3].cells[0].innerHTML;
var cell8 = table.rows[3].cells[1].innerHTML;
var cell9 = table.rows[3].cells[2].innerHTML;
How would I go about doing this? I would also want to great a variable that could represent all the var cell(s) like this
tableData = [] tableData.append(var cell7 = etc..)
so then I could take the tableData and:
localStorage.setItem("tableData", tableData);
so then I could call this table data variable inside another html file.
I would also like to localStorage the variable lines themselves so I could call them individually as-well.
localStorage.setItem("item-name-1", cell1);
How would I got about doing this?
Important Note: At the start of my html page the table is empty. I then append the data using several inputs and an add button.
Any Help is appreciated Thank you.
Use a variable with an array:
var table, cell, i, r, noofrows;
table = document.getElementById("items-table");
noofrows = table.rows.length;
for (i = 0, r = 0, cell = []; r < noofrows; i++, r++) {
cell[i] = table.rows[r].cells[0].innerHTML;
cell[i+1] = table.rows[r].cells[1].innerHTML;
cell[i+2] = table.rows[r].cells[2].innerHTML;
}
Then the first cell will be assigned to the variable cell[0], the second will be cell[1], etc. For example, document.write(cell[0]) will write "Item" (from your previous question).
document.write(cell[1]) will write "Size".
document.write(cell[3]) will write the first cell of row 2.
You're looking for an array, in your case probably an array of arrays:
let cells = Array.prototype.map.call(document.getElementById("items-table").rows, row => {
return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
});
Live Example:
let cells = Array.prototype.map.call(document.getElementById("items-table").rows, row => {
return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
});
console.log("cells:", cells);
.as-console-wrapper {
max-height: 100% !important;
}
<table id="items-table">
<tbody>
<tr>
<td>Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
<tr>
<td>Row 2 Cell 1</td>
<td>Row 2 Cell 2</td>
<td>Row 2 Cell 3</td>
</tr>
<tr>
<td>Row 3 Cell 1</td>
<td>Row 3 Cell 2</td>
<td>Row 3 Cell 3</td>
</tr>
<tr>
<td>Row 4 Cell 1</td>
<td>Row 4 Cell 2</td>
<td>Row 4 Cell 3</td>
</tr>
</tbody>
</table>
The Array.prototype.map.call part lets us use Array's built-in map function on rows and cells even though they aren't arrays, but are array-like. Alternatively, you could actually turn them into arrays with Array.from:
let cells = Array.from(document.getElementById("items-table").rows).map(row => {
return Array.from(row.cells).map(cell => cell.innerHTML);
});
Live Example:
let cells = Array.from(document.getElementById("items-table").rows).map(row => {
return Array.from(row.cells).map(cell => cell.innerHTML);
});
console.log("cells:", cells);
.as-console-wrapper {
max-height: 100% !important;
}
<table id="items-table">
<tbody>
<tr>
<td>Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
<tr>
<td>Row 2 Cell 1</td>
<td>Row 2 Cell 2</td>
<td>Row 2 Cell 3</td>
</tr>
<tr>
<td>Row 3 Cell 1</td>
<td>Row 3 Cell 2</td>
<td>Row 3 Cell 3</td>
</tr>
<tr>
<td>Row 4 Cell 1</td>
<td>Row 4 Cell 2</td>
<td>Row 4 Cell 3</td>
</tr>
</tbody>
</table>
Storing that in local storage is simply a call to JSON.stringify:
localStorage.setItem("tableData", JSON.stringify(cells));
Restoring it from local storage:
var cells = JSON.parse(localStorage.getItem("tableData") || "[]");
(The || "[]" part provides a default — an empty array — for when there is no tableData stored.)

Selecting rows and colums of a table using jquery and update its content

I have a HTML table followed by a simple form which accepts the table row and column like below
<table border="1" style="width:100%">
<tr>
<td>Row 1 Col1</td>
<td>Row 1 Col2</td>
<td>Row 1 Col3</td>
<td>Row 1 Col4</td>
<td>Row 1 Col5</td>
<td>Row 1 Col6</td>
</tr>
<tr>
<td>Row 2 Col1</td>
<td>Row 2 Col2</td>
<td>Row 2 Col3</td>
<td>Row 2 Col4</td>
<td>Row 2 Col5</td>
<td>Row 2 Col6</td>
</tr>
<tr>
<td>Row 3 Col1</td>
<td>Row 3 Col2</td>
<td>Row 3 Col3</td>
<td>Row 3 Col4</td>
<td>Row 3 Col5</td>
<td>Row 3 Col6</td>
</tr>
</table>
<form>
<input type="text" placeholder="Row" value="row"/>
<input type="text" placeholder="Column" value="column"/>
<button id="submitButton" type="submit"> Submit </button>
</form>
Table row and column can vary and can have n number of rows and columns. What i would like to do is based on the user input (selecting rows and column and submitting it) i want to update the content of the user selected row and column to say "Hello". if user selects a column, row combination which is not available alert an error message. How could i do this in jquery.
Thanks in Advance.
$('#submitButton').click(
function(){
var numrow = $('#numrow').val();
var numcol = $('#numcol').val();
var enttotal = numrow * numcol;
var lenrow = $('.dataupdate tr').length;
var lencol = $('.dataupdate tr:first-child td').length;
var tcol = $('.dataupdate tr td').length;
if(numrow <= lenrow && numcol <= lencol && enttotal <= tcol){
$('.dataupdate tr:nth-child('+numrow+') td:nth-child('+numcol+')').html('Hello')
}
else { alert('there is no such column in this table'); }
});
this is working fiddle link
http://jsfiddle.net/6vj92vcp/
You can use like this,
$("#submitButton").click(function (e) {
e.preventDefault();
var r = parseInt($("#row").val()) - 1;
var c = parseInt($("#column").val()) - 1;
$("table").find("tr").eq(r).find("td").eq(c).text("hello");
});
Fiddle
It is an undex based approach. First you need to find the nth row using the .eq() selector. Since the index is starting from 0, you need to decrement the actual value by 1.
You can use .find() method to get all the child elements.
$(document).ready(function(){
$("#submitButton").click(function(){
var row = parseInt($("#rows").val())-1;
var col = parseInt($("#cows").val())-1;
var greeting = "hello";
if(isNaN(row)|| isNaN(col)) {
alert('Please enter a valid row and column number');
return false;
}
var x = $("table").find("tr").eq(row).find("td").eq(col);
if(x.length==0)
alert('Such a row and column not found ');
else if(x.text()==greeting)
alert("Already selected ");
else
x.text(greeting);
return false;
});
});
http://jsfiddle.net/tintucraju/fm0sL4s9/

Get HTML table cells values in a rows by clicking on it

How can I get values of TDs inside an HTML table?
i.e.
| ID | cell 1 | cell 2 |
| 1 | aaaa | a2a2a2 |
| 2 | bbbb | b2b2b2 |
| 3 | cccc | c2c2c2 |
So now if I click on the cell value: "bbbb" I want to get all the values of selected row:
$id='2'; $cell_1='bbbb'; $cell_2='b2b2b2';
NOTE: I'd like to use JavaScript and not jQuery.
You can use event.target.innerText for javascript and $(event.target).text() for jQuery, jQuery is preferred solution as it handles cross browser competibilities.
Using only javascript
Live Demo
Html
<table id="tableID" onclick="myFun(event)" border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>​
Javascript
function myFun(e){
alert(e.target.innerText); //current cell
alert(e.target.parentNode.innerText); //Current row.
}​
Using jQuery
Live Demo
Html
<table id="tableID" border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>​
Javascript
$('#tableID').click(function(e){
alert($(e.target).text()); // using jQuery
})
var table = document.getElementById('tableID'),
cells = table.getElementsByTagName('td');
for (var i=0,len=cells.length; i<len; i++){
cells[i].onclick = function(){
console.log(this.innerHTML);
/* if you know it's going to be numeric:
console.log(parseInt(this.innerHTML),10);
*/
}
}
from here
Hope This helps you. It contains cross browser script.
<html>
<head>
<script type="text/javascript">
function myFun(e){
if(!e.target)
alert(e.srcElement.innerHTML);
else
alert(e.target.innerHTML);
}
</script>
</head>
<body>
<table id="tableID" onclick="myFun(event)" border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
</body>
</html>
Use of jquery will be easy..
$("#tableId").find("td").click(function(event){
var listOfCell=$(this).siblings();
for(i=0;i<listOfCell.length;i++){
alert($(listOfCell[i]).text());
}
});

Can I iterate through table using JQuery and collect values in three arrays?

Can I iterate through table with id="tbl" using JQuery with three columns and collect this value in three javascript arrays ?
Here is an example
http://jsfiddle.net/SpE7F/
Javascript:
$().ready(function(){
var trArray = []
$('#tbl tr').each(function(){
var tdArray = []
$(this).find('td').each(function(){
tdArray.push($(this).text())
})
trArray.push(tdArray)
})
//console.log(trArray)
for(row = 0; row < trArray.length; row++){
for(cell = 0; cell < trArray[row].length; cell++){
alert('row: '+row+', cell: '+cell+' value: '+trArray[row][cell])
}
}
})
HTML
<table id="tbl" border="1">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</table>
you can use this to find the Nth element in a 'tr'
so $("#tbl td").eq(2) would get you the 3rd 'td'
Something like this should work.
firstCols = new Array();
secondCols = new Array();
thirdCols = new Array();
$(function() {
$("#tbl tr").each(function(i) {
var firstChild = $(this).children().first();
firstCols[i] = firstChild.text();
secondCols[i] = firstChild.next().text();
thirdCols[i] = firstChild.next().next().text();
});
});
You can loop through the columns and organize it via the index. This isn't a semantic table, but if you add the header/body just make sure to change the selector appropriately as well.
var arr = [];
$('#tbl td').each(function(){
var colId = $(this).index();
var rowId = $(this).parent().index();
if (arr[colId] == undefined) {
arr[colId] = [];
}
arr[colId][rowId] = $(this).html();
});
console.log(arr);
Here's the fiddle : http://jsfiddle.net/MfxA9/
Here's the HTML
<table id='tbl'>
<tr>
<td>Col 1 : Row 1</td>
<td>Col 2 : Row 1</td>
<td>Col 3 : Row 1</td>
</tr>
<tr>
<td>Col 1 : Row 2</td>
<td>Col 2 : Row 2</td>
<td>Col 3 : Row 2</td>
</tr>
<tr>
<td>Col 1 : Row 3</td>
<td>Col 2 : Row 3</td>
<td>Col 3 : Row 3</td>
</tr>
<tr>
<td>Col 1 : Row 4</td>
<td>Col 2 : Row 4</td>
<td>Col 3 : Row 4</td>
</tr>
</table>
Sure you can:
// Column-arrays
var col1 = new Array();
var col2 = new Array();
var col3 = new Array();
// Cache table
var table = $('#tbl');
// Iteratate over rows
var rows = table.find('tr');
rows.each(function() {
// Iterate over columns
var columns = this.children('td');
// Save column-values in separate arrays
col1.push(columns[0].html());
col2.push(columns[1].html());
col3.push(columns[2].html());
});

Categories

Resources