I have a problem I been suffering on for a couple hours now.
The context is, I need to make a button with action listener in JavaScript and add it into a table.
Here is the code I have
var _button = document.createElement("button");
_button.data = _a;
_button.innerHTML = 'click me';
_button.onclick = function()
{
alert("hello, world");
}
var table = document.getElementById("tableOnline");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var _weakbutton = _button.outerHTML;
_weakbutton.onclick = function()
{
alert("hello, world");
}
cell1.innerHTML = "h";
cell2.innerHTML = "o";
cell3.innerHTML = _weakbutton;
The code works if I add the create the button and add it onto the body (without weakButton), but how can I make it work into a table?
Kind regards,
Zhendos.
EDIT:
Because requested, here is the table we talk about.
<div class = "container">
<div class = "table">
<thead id = "thead">
<tr>
<th> firstname <th>
<th> lastname </th>
<th> organisation </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Instead of var _weakbutton = _button.outerHTML; create a copy of the button with var _weakbutton = _button.cloneNode(true);. This will create a new button, based on your original one.
Because this is now a button node, you can't add it with cell3.innerHTML = _weakbutton; but have to use cell3.appendChild( _weakbutton );
So, with your code it would be
var _button = document.createElement("button");
_button.data = "hi";
_button.innerHTML = 'click me';
_button.onclick = function()
{
alert("hello, world");
}
var table = document.getElementById("tableOnline");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var _weakbutton = _button.cloneNode(true)
_weakbutton.onclick = function()
{
alert("hello, world");
}
cell1.innerHTML = "h";
cell2.innerHTML = "o";
cell3.appendChild( _weakbutton );
<table id="tableOnline"></table>
Related
So I am creating a website that allows users to enter information about books they've read and it enters the information into a table. But I want the user to be able to delete a specific row (book) from the table if they click on a button.
I've added a click eventListener to the delete buttons but right now it is only deleting the row at the 0th index and sometimes it's deleting multiple rows at a time. I'm not sure why.
function addBooks() {
let info = document.getElementById("author").value;
let info2 = document.getElementById("title").value;
let info3 = document.getElementById("genre").value;
let info4 = document.getElementById("reviews").value;
document.getElementById("author").value = "";
document.getElementById("title").value = "";
document.getElementById("genre").value = "";
document.getElementById("reviews").value = "";
let obj = {
author: info,
title: info2,
genre: info3,
review: info4,
};
let table = document.getElementById("table");
const row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = `${obj.author}`;
cell2.innerHTML = `${obj.title}`;
cell3.innerHTML = `${obj.genre}`;
cell4.innerHTML = `${obj.review}<button id="delete" class="delete">Delete Book</button>`;
document.querySelectorAll(".delete").forEach((item) => {
item.addEventListener("click", (event) => {
document.getElementById("table").deleteRow(1);
});
});
}
<body>
<div class="container">
<h1 class="heading">Your Books</h1>
<p class="subHeading">Author</p>
<input id="author"></input>
<p class="subHeading">Title</p>
<input id="title"></input>
<p class="subHeading">Genre</p>
<input id="genre"></input>
<p class="subHeading">Reviews</p>
<input id="reviews"></input>
</div>
<button class="btn" onclick="addBooks()" id="button">Submit</button>
<table id="table">
<tr>
<th>Author</th>
<th>Title</th>
<th>Genre</th>
<th>Reviews</th>
</tr>
</table>
<script src="books.js"></script>
</body>
So the JavaScript allows the user to add new rows of information to the table. But they need to be able to delete specific rows as they click the delete buttons on that specific row.
I've added event listeners to the delete buttons but the function that reacts to the buttons clicking is only deleting the first row instead of the row that the button is clicked on.
Can anyone explain how to do this?
There are many ways to delete the row, just as other answers have demonstrated.
The reason why your code is only deleting the first entry is because you put deleteRow(1), which means "delete the row at index 1". Since the row at index 0 is your header, row at index 1 is your first entry.
And the reason why it sometimes delete everything is because you add event listener every time you add a new book. When you add the first book, the delete button will keep row index 1 as the reference to delete. When you add the second book, you add another event listener to the same button to delete the new row that you're adding. The previous reference is now at index 2. When you click that button, it will delete both the rows and index 1 and 2.
This is another way of doing it in JavaScript, using your code:
function addBooks() {
let info = document.getElementById("author").value;
let info2 = document.getElementById("title").value;
let info3 = document.getElementById("genre").value;
let info4 = document.getElementById("reviews").value;
document.getElementById("author").value = "";
document.getElementById("title").value = "";
document.getElementById("genre").value = "";
document.getElementById("reviews").value = "";
let obj = {
author: info,
title: info2,
genre: info3,
review: info4,
};
let table = document.getElementById("table");
const row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var deleteButton = document.createElement('button');
deleteButton.type = 'button';
deleteButton.textContent = 'Delete Book';
deleteButton.addEventListener('click', (event) => {
var row = deleteButton.parentNode.parentNode;
row.parentNode.removeChild(row)
})
cell1.innerHTML = `${obj.author}`;
cell2.innerHTML = `${obj.title}`;
cell3.innerHTML = `${obj.genre}`;
cell4.innerHTML = `${obj.review}`;
cell4.appendChild(deleteButton);
}
First of all, </input> is not a valid HTML tag, you should use <input type="..." /> instead.
There are many solutions to delete a row in a table, here is one. On click of the button, you find its closest tr and you remove it :
function addBooks() {
let info = document.getElementById("author").value;
let info2 = document.getElementById("title").value;
let info3 = document.getElementById("genre").value;
let info4 = document.getElementById("reviews").value;
document.getElementById("author").value = "";
document.getElementById("title").value = "";
document.getElementById("genre").value = "";
document.getElementById("reviews").value = "";
let obj = {
author: info,
title: info2,
genre: info3,
review: info4,
};
let table = document.getElementById("table");
const row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = `${obj.author}`;
cell2.innerHTML = `${obj.title}`;
cell3.innerHTML = `${obj.genre}`;
cell4.innerHTML = `${obj.review}<button onclick="this.closest('tr').remove()">Delete Book</button>`;
}
<body>
<div class="container">
<h1 class="heading">Your Books</h1>
<p class="subHeading">Author</p>
<input type="text" id="author" />
<p class="subHeading">Title</p>
<input type="text" id="title" />
<p class="subHeading">Genre</p>
<input type="text" id="genre" />
<p class="subHeading">Reviews</p>
<input type="text" id="reviews" />
</div>
<button class="btn" onclick="addBooks()" id="button">Submit</button>
<table id="table">
<tr>
<th>Author</th>
<th>Title</th>
<th>Genre</th>
<th>Reviews</th>
</tr>
</table>
<script src="books.js"></script>
</body>
Just create an onclick on your button that passes in its parent element using this.parentElement:
cell4.innerHTML = `${obj.review}<button id="delete" class="delete" onclick="deleteBook(this.parentElement)">Delete Book</button>`;
Then, remove its parent in the function:
function deleteBook(elem){
elem.parentElement.removeChild(elem);
}
I am using the following code to add a new row dynamically to my HTML.
When I enter the details and hit submit, the new row shows up momentarily and disappears.
What am I doing wrong?
function addNewRow(){
var tab = document.getElementById("table"),
newRow = tab.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3),
cell5 = newRow.insertCell(4),
date = document.getElementById("date-input").value,
time = document.getElementById("time-input").value,
amount = document.getElementById("amount-input").value,
source = document.getElementById("source-input").value,
destination = document.getElementById("dest-input").value;
cell1.innerHTML = date;
cell2.innerHTML = time;
cell3.innerHTML = amount;
cell4.innerHTML = source;
cell5.innerHTML = destination;
}
var btn = document.getElementById("button");
btn.addEventListener('click', function(){
addNewRow();
})
I have a table of rows and a button to delete it in each row.
I can remove a row bot the problem is that I need to update the value deleteRow(nb_of_rows) in every time I remove a row
This is the table code in HTML
<input type="button" id="insert_row" value="Insert Row" onclick="insert_row()" >
<br><br>
<table id="mytable" width="100%" border="2" >
<tr>
<th>Sr.</th>
<th>Item Name</th>
<th>Price</th>
<th>Count</th>
<th>Total</th>
<th>Delete</th>
</tr>
</table>
and this is JavaScript code
var srn = 0;
function insert_row(){
var table = document.getElementById("mytable")
var nb_of_rows = document.getElementById("mytable").rows.length;
var row = table.insertRow(nb_of_rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = changeSR();
var delete_btn = document.createElement("input");
delete_btn.type = "button";
delete_btn.className = "btn";
delete_btn.value = "Delete";
cell6.appendChild(delete_btn);
delete_btn.onclick = function deleteRow(){
return document.getElementById("mytable").deleteRow(nb_of_rows);
}
}
function changeSR(){
return srn = srn + 1 ;
}
and this is an online share of my code
enter link description here
The issue occurs because the index in nb_of_rows is in danger of being out of date by the time the button is clicked (especially if other rows and have been added and deleted in the meantime). Therefore it will either delete the wrong row, or crash because the index doesn't exist in the table any more.
The solution is fairly simple: make the button get the parent row it belongs to, and then get that row's current index at the point of deletion, rather than relying on the index it had when it was added.
Usefully the row element has an index property telling you its current index in the table body, which makes this solution possible.
Here's the event code you need:
delete_btn.onclick = function deleteRow() {
var row = this.parentElement.parentElement; //get the parent of the parent (i.e. the first parent is the table cell, and the parent of that is the row)
document.getElementById("mytable").deleteRow(row.rowIndex);
}
(BTW it makes no sense really to have a return statement in an event handler, since the control returns to somewhere in the JS event-handling engine, not to your code, so I removed that at the same time.)
Demo:
var srn = 0;
function insert_row() {
var table = document.getElementById("mytable")
var nb_of_rows = document.getElementById("mytable").rows.length;
var row = table.insertRow(nb_of_rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = changeSR();
var delete_btn = document.createElement("input");
delete_btn.type = "button";
delete_btn.className = "btn";
delete_btn.value = "Delete";
cell6.appendChild(delete_btn);
delete_btn.onclick = function deleteRow() {
var row = this.parentElement.parentElement;
document.getElementById("mytable").deleteRow(row.rowIndex);
}
}
function changeSR() {
return srn = srn + 1;
}
<input type="button" id="insert_row" value="Insert Row" onclick="insert_row()">
<br><br>
<table id="mytable" width="100%" border="2">
<tr>
<th>Sr.</th>
<th>Item Name</th>
<th>Price</th>
<th>Count</th>
<th>Total</th>
<th>Delete</th>
</tr>
</table>
I'm doing a school project in which I'm creating web pages to allow users to input and then display it on another page. I am only using JavaScript, HTML and CSS for the web pages.
On the "Create An Event" page there is a form. I have saved all the input into local storage but now I am not sure how to retrieve the data to display it on the "Events Created" page (which shows the past events that the user has created).
Here is my JavaScript code:
document.addEventListener("DOMContentLoaded", docIsReady);
var eventHist;
function docIsReady() {
eventHist = localStorage.getItem("createEvent");
if (eventHist == null) {
eventHist = [];
} else {
eventHist = JSON.parse(eventHist);
}
//building of the table
for (var i = 0; i < eventHist.length; i++) {
var row = document.getElementById("list").insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = eventHist[i].name;
cell2.innerHTML = eventHist[i].positions;
cell3.innerHTML = eventHist[i].venue;
cell4.innerHTML = eventHist[i].date;
cell5.innerHTML = eventHist[i].timeStart;
cell6.innerHTML = eventHist[i].timeEnd;
}
}
function addHistory() {
var obj;
var name = document.getElementById("name").value;
if (!checkExisting(name)) {
var positions = document.getElementById("pos").value;
var venue = document.getElementById("venue").value;
var date = document.getElementById("date").value;
var starttime = document.getElementById("timeStart").value;
var endtime = document.getElementById("timeEnd").value;
obj = {
"name": name,
"venue": venue,
"date": date,
"timeStart": starttime,
"timeEnd": endtime
};
eventHist.push(obj)
localStorage.setItem("createEvent", JSON.stringify(obj));
}
//add to table
var row = document.getElementById("list").insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = obj.name;
cell2.innerHTML = obj.positions;
cell3.innerHTML = obj.venue;
cell4.innerHTML = obj.date;
cell5.innerHTML = obj.timeStart;
cell6.innerHTML = obj.timeEnd;
}
function sortTable() {
eventHist.sort(function(obj1, obj2) {
if (obj1.date > obj2.date)
return 1;
else if (obj1.date < obj2.date)
return -1;
else
return 0;
});
console.log("Sorted");
//reload table
var tableRow = document.querySelectorAll("#list tr");
console.log(tableRow);
console.log("no of rows=" + tableRow.length);
for (var i = 0; i < eventHist.length; i++) {
var row = document.getElementById("list").insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = eventHist[i].name;
cell2.innerHTML = eventHist[i].positions;
cell3.innerHTML = eventHist[i].venue;
cell4.innerHTML = eventHist[i].date;
cell5.innerHTML = eventHist[i].timeStart;
cell6.innerHTML = eventHist[i].timeEnd;
}
document.getElementById("list").style.display = "table";
}
Here is my HTML code:
<table border="1px" id="list" onload="addRow();">
<tr>
<th>Name of event</th>
<th>Positions</th>
<th>Venue</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<!--<th>Points Awarded</th>-->
</tr>
</table>
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
I am appending data dynamically to my table as:
function myFunctionEdit()
{
var table = document.getElementById("nomiTable");
var len = table.rows.length;
var row = table.insertRow(len);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = len;
cell2.innerHTML = name;
cell3.innerHTML = dob;
cell4.innerHTML = relation;
cell5.innerHTML = share;
cell6.innerHTML = "<a href = \"#\" data-toggle=\"modal\" data-target=\"#editNomiModal\" id = \"editNominHref\" name = \"editNominHref\" ><img border=\"0\" alt=\"Edit Nominee\" src=\"images/edit.png\" width=\"15\" height=\"15\"/></a>";
$('#editNomiModal').modal('hide');
return false;
}
My table structure is:
<table id = "nomiTable" name = "nomiTable" class="table table-striped table-hover">
<thead>
<tr>
..
</tr>
</thead>
<tbody>
<tr>
..Dynamically generated columns...
<td>
<a href = "#" data-toggle="modal" data-target="#editNomiModal" id = "editNominHref" name = "editNominHref" >
<img border="0" alt="Edit Nominee" src="images/edit.png" width="15" height="15"/>
</a>
</td>
</tr>
JQuery Function on #editNominHref click:
$("#editNominHref").on('click', function(e)
{
alert($(this).closest('tr').index());
});
Problem:
The method does not work on dynamically generated Edit Hrefs. Any help would be highly appreciated.
Use event delegation for same.
$(document).on('click', '#editNominHref', function(e)
{
alert($(this).closest('tr').index());
});