Button to remove row of table is not working using Javascript - javascript

This is the table in which I have used button to remove of table.
<table>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>User Name</th>
<th>Email</th>
<th>Remove</th>
</tr>
<tr>
<td>Sujan6</td>
<td>Bikram5</td>
<td>Thapa</td>
<td>Sujan6</td>
<td>Sujan#gmail5</td>
<td><button class="button button3">Remove</button></td>
</tr>
<tr>
<td>Sujan7</td>
<td>Bikram6</td>
<td>Thapa</td>
<td>Sujan7</td>
<td>Sujan#gmail5</td>
<td><button class="button button3">Remove</button></td>
</tr>
</table>
This is the Javascript code with which I am trying to remove row of table. This code show error of:
"TypeError: Cannot read property 'parentNode' of undefined" at the line of " var tr = td.target.parentElement;"
var deleteRecord = document.getElementsByClassName('button button3');
for (var i = 0; i < deleteRecord.length; i++) {
deleteRecord[i].addEventListener('click', removeItem);
}
function removeItem(e) {
event.preventDefault();
if (confirm('Are You Sure')) {
var td = e.target.parentElement;
var tr = td.target.parentElement;
tr.parentElement.removeChild('tr');
}
}

td is not an event, so it doesn't have a target. Accessing this will cause the error you are seeing. Access the parentElement directly on td.
You also need to remove the quotes around tr when removing the element.
function removeItem(e) {
event.preventDefault();
if (confirm('Are You Sure')) {
var td = e.target.parentElement;
var tr = td.parentElement;
tr.parentElement.removeChild(tr);
}
}

Related

Hide rows in a column with vanilla JavaScript according to text content

I have a table like this:
<table id="mytable" class="table">
<tr>
<th>Author</th>
<th>Title</th>
<th>Year</th>
<th>Digitised</th>
</tr>
</table
I'd like to have a button which, when clicked, hides or shows the rows which contain a 'Yes' (or a check, or a specific element) in the 'Digitised' column.
This is the JavaScript I've come up so far
let table, tr, td, i, t;
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for(t=0; t<tds.length; t1++) {
let td = tds[t][3];
if (td) {
if (td.innerHTML.indexOf('Yes') > -1) {
tr[i].style.display = 'none';
}
}
}
}
This doesn't work. How can I achieve what I want?
You have the wrong id in your Javascript, the table id is "mytable" (in lower case) but your js code is trying to find "myTable" which is camel case,
Anyways here is a sample of code that do what you need:
var areRowsDisplayed = true
function toggleRows() {
const rows = document.querySelectorAll('#mytable > tbody > tr')
Array.prototype.slice.call(rows).forEach(row => {
let dataField = row.querySelectorAll('td')[3]
if(dataField.innerText.toLowerCase() == 'yes') {
row.style.display = !areRowsDisplayed ? '': 'none'
}
})
areRowsDisplayed = !areRowsDisplayed
}
document.querySelector('#toggleRows').addEventListener('click',e => toggleRows())
<button id='toggleRows'>Hide/Show</button>
<table id="mytable" class="table">
<thead>
<tr>
<th>Author</th>
<th>Title</th>
<th>Year</th>
<th>Digitised</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pin Pon</td>
<td>The new song</td>
<td>1991</td>
<td>No</td>
</tr>
<tr>
<td>Cloudies</td>
<td>Fly with me</td>
<td>1986</td>
<td>Yes</td>
</tr>
</tbody>
</table>
This basically has a button that run a javascript function, and within that function we loop into each table row and hide/show the rows that meet certain criteria
I have added a global variable to check what is the current status (if the rows are hidden already) only for this sample purposes, you must be storing that in some context depending on the framework you are using

Connect button to display data in a html table using Javascript

I have a dynamically generated table that uses array of JS objects. I'm also adding a "View details" on each row. What I need is to be able to display data from the same array of objects in a different table.
I tried to add event listener to the buttons, but they either iterate through all of the rows or don't display anything
function drawTable(tbody) {
var tr, td;
tbody = document.getElementById(tbody);
for (var i = 0; i < products.length; i++) // loop through data source
{
tr = tbody.insertRow(tbody.rows.length);
td = tr.insertCell(tr.cells.length);
td.innerHTML = products[i].ProductName;
td = tr.insertCell(tr.cells.length);
td.innerHTML = products[i].UnitsInStock;
td = tr.insertCell(tr.cells.length);
// View Details button
td = tr.insertCell(tr.cells.length);
button = document.createElement('button');
button.textContent = ('View Details')
td.appendChild(button)
}
}
<div class="table-wrapper">
<table id="display-table" class="fl-table">
<thead>
<tr>
<th>Product Name</th>
<th>Units In Stock</th>
<th>View Details</th>
</tr>
</thead>
<tbody id="table-data">
</tbody>
</table>
</div>
<h2>Product Details</h2>
<div class="table-wrapper">
<table class="fl-table">
<thead>
<tr>
<th>Product Name</th>
<th>Product Category</th>
<th>Product Description</th>
</tr>
</thead>
<tbody id="table-details">
</tbody>
</table>
</div>
Below button.textContent = ('View Details') add
button.onclick = (n=> event=> {
console.log('click on', products[n]) // you handler here
})(i); // set current loop "i" as parameter "n" value
we wrap function event=>... in n=>... to pass current i value - without this the i would be set always to last iteration value.

How to find the corresponding th to a given td?

Basically the same question as How can I get the corresponding table header (th) from a table cell (td)? but not jQuery specific.
From a given <td> is there an easy way to find the corresponding <th>?
<table width="100%" id="stock">
<tr>
<th>Name</th>
<th>Type</th>
<th>Quantity</th>
<th>Options</th>
</tr>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td>-1</td>
<td>...</td>
</tr>
I'd like something doing this:
document.getElementById('target').correspondingTH // would return HTMLObject <th>Type</th>
An ideal answer might contain both a jQuery way to do it and a vanilla one but I'm personally looking for a vanilla one.
Pure JavaScript's answer.
var index = Array.prototype.indexOf.call(your_td.parentNode.children, your_td)
var corresponding_th = document.querySelector('#your_table_id th:nth-child(' + (index+1) + ')')
As posted here in the more jQuery specifc question: https://stackoverflow.com/a/37312707/1524913
HTML table model gives easier solution. jquery in this case is more sophisticated. I tested following table:
<table style="width:100%" id="stock">
<tbody>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td>-1</td>
<td>...</td>
</tr>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td>-1</td>
<td>...</td>
</tr>
</tbody>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td colspan="2">-1</td>
<!--<td>...</td>-->
</tr>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Quantity</th>
<th>Options</th>
</tr>
</thead>
</table>
Script without jquery is simple and straightforward.
window.onload = function () {
var tbl = document.getElementById('stock');
var tds = document.getElementsByTagName('td');
for (var i = 0, td; td = tds[i]; ++i) {
td.onclick = function () {
var tr = this.parentNode;
console.log(tbl.rows[0].cells[this.cellIndex].innerHTML);
}
}
}
jquery also is useful.
$(document).ready(function () {
$('#stock td').click(function () {
console.log($(this).parents('table').find('tr:first-child').children('th:nth-child(' + (this.cellIndex + 1) + ')').html());
});
});
<thead> can be placed at the top, at the bottom, and between rows. thead inside tbody is obvious error but browser fixes it. Scripts work in any case.
I think you need to step through the TH colSpans to exactly match the TD
Try
function getHeadCell(td) {
var index = Array.prototype.indexOf.call(td.parentNode.children, td);
var table = td;
while (table && table.tagName != 'TABLE') table = table.parentNode;
var cx = 0;
for (var c = 0; cx <= index; c++) cx += table.rows[0].cells[c].colSpan;
return table.rows[0].cells[c - 1];
}
See https://jsfiddle.net/Abeeee/upt75s2x/34/ for a working example

How to Get InnerHTML for Table Cell instead of an object or NaN

I am attempting to create a string that contains all of the data within an HTML table using JavaScript (open to changing to JQuery). By using this method below, I receive an NaN value, instead of the data (numbers).
function Ard() {
var table = document.getElementById("tblData");
var dataStr = "";
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
var toAdd = col;
dataStr += toAdd;
}
}
};
I have also tried a jQuery method but it only returned an HTML object. It should be noted that when printing the 'col' value to the console, the data is collected properly (actual values).
The table I'm using is editable by the user, but it saves as a standard HTML table. Here is the basic code for the table below if it helps solve the problem.
<table id="tblData" class="table table-hover">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Treatment Number</th>
<th>Cell Number</th>
<th>Waste Container Number</th>
</tr>
</thead>
<tbody></tbody>
</table>
Any ideas towards how to get the innerHTML and add it properly to the string?
I would also like to do this with a row by column loop (set of two for or each loops maybe?) so that I know what column I'm grabbing from.
Since you are OK to use jquery,
var dataStr = "";
$('#tblData > tbody').each(function(e) {
dataStr += $(this).text();
});
console.log(dataStr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tblData" class="table table-hover">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Treatment Number</th>
<th>Cell Number</th>
<th>Waste Container Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>10101</td>
<td>20202</td>
<td>30303</td>
<td>40404</td>
<td>50505</td>
</tr>
<tr>
<td>wowowo</td>
<td>sksksk</td>
<td>alalal</td>
<td>qpqpqp</td>
<td>zmzmzm</td>
</tr>
</tbody>
</table>
If you want the dataStr to have the <td> tags also, you should use,
dataStr += $(this).html()
EDIT
If you also want to access the current column index, you can use this. But here, the dataStr would finally contain a single line string concatenating all the texts inside <td> tags.
$('#tblData > tbody > tr > td').each(function(e) {
var currentColNo = $(this).index();
dataStr += $(this).html();
});
With jQuery you could select all rows and the iterate over them and get the text:
var str = "", values = [];
$("#tblData").find('tbody').find('tr').each(function() {
//You can concatenate a string or push the values to an array
str += $(this).text();
values.push($(this).text());
});
console.log(str, values);
You can do it with pure js:
function Ard() {
var table = document.querySelectorAll("#tblData tr th");
var dataStr = "";
for (var i = 0; i < table.length; i++) {
dataStr += table[i].innerHTML;
}
};
JSFiddle Demo
This will get you all text from the table <td>s and post it into a textarea (just for demonstration purposes):
$('#out').val($('#tblData td').text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tblData" class="table table-hover">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Treatment Number</th>
<th>Cell Number</th>
<th>Waste Container Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>some</td><td>extra</td><td>data</td>
</tr>
</tbody>
</table>
<textarea id="out" rows=10 cols=60></textarea>
Update:
If you "just" want to put the <td> contents into a single variable you could do:
var str=$('#tblData td').text()
I extended your example so you will actually get a result.

plain text to input text on click using javascript

I have a table that needs edit buttons in each row, on click the plain text should become input, I've read many tutorial but i understand none as i am new to javascript, can anyone help?
this is what i started with:
<script type="text/javascript">
function Edit(clickedButton){
//get row of the clicked button
var row = clickedButton.closest('tr');
'retrieve each info
var tdID = row.cells[0];
var tdFirstName = row.cells[1];
var tdLastName = row.cells[2];
var tdDOB = row.cells[3];
var tdGender = row.cells[4];
var tdStatud = row.cells[5];
</script>
and this in my table:
<table id="table" class="table .table-bordered" style="width:80%">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>DOB</th>
<th>Gender</th>
<th>Martial Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr id="frow">
<td>1</td>
<td>Samir</td>
<td>Khattar</td>
<td>1-12-1990</td>
<td>Male</td>
<td>Married</td>
<td>
<button onclick="Edit(this)">Edit</button>
<button onclick="Delete(this)">Delete</button>
</td>
</tr>
</tbody>
</table>
and whats the difference between .innerhtml and .html
At first take a form to get input as you want. Then hide the input area as default. And show As you are showing your table inside the form. If any of the button is clicked then the hidden input area will be shown and the the default table row will be hidden. This is the idea to do so.
innserHTML is a javascript DOM property. It return DOM's inner html, it can also be used as to change the inner html of that dom. On the other hand, html() is a jQuery library function to do the same work. May be this method of jQuery actually use the innserHTML property.
To know about the performance of innerHTML and & html() you can check out this link: .append VS .html VS .innerHTML performance
Best of luck
Simply do like this...it will work...
$(function () {
$("#table td").click(function (e) {
e.preventDefault(); // <-- consume event
e.stopImmediatePropagation();
$this = $(this);
if ($this.data('editing')) return;
var val = $this.text();
$this.empty()
$this.data('editing', true);
$('<input type="text" class="editfield">').val(val).appendTo($this);
});
putOldValueBack = function () {
$("#table .editfield").each(function(){
$this = $(this);
var val = $this.val();
var td = $this.closest('td');
td.empty().html(val).data('editing', false);
});
}
$(document).click(function (e) {
putOldValueBack();
});
});
//Refer this example
<table id="table">
<tr>
<th>RecID</th>
<th>Col1</th>
<th>Col2</th>
</tr>
<tr>
<td>RecID</td>
<td>Val1.1</td>
<td>Val1.2</td>
</tr>
<tr>
<td>RecID</td>
<td>Val2.1</td>
<td>Val2.2</td>
</tr>
<tr>
<td>RecID</td>
<td>Val3.1</td>
<td>Val3.2</td>
</tr>
</table>
Try this
function Edit(clickedButton){
var getTR = clickedButton.parentNode.parentNode;
var getLength = getTR.childElementCount;
var getTds = getTR.querySelectorAll("td")
for (i in getTds){
if(i < (getLength-1)){
getTds[i].innerHTML = "<input type='text' value='"+getTds[i].innerHTML+"'>";
}
}
}

Categories

Resources