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);
}
Related
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 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>
So im trying to make a table where it adds the content from 3 Textareas.
I succeeded in adding them but only with innerHTML but now im struggling to replace innerHTML with a DOM style(like appendChild etc.)
Table:
<header class="datagrid">
<h1> Zitatenbaum </h1>
<table id ="ZitatenOrdnung">
<thead>
<tr>
<th>Zitat</th>
<th>Autor</th>
<th>Ihre Bewertung </th>
</tr>
</thead>
</table>
</header>
Form:
<form>
<textarea rows = "5" cols = "60" placeholder="Zitat einfügen" id = "Zitat1"> </textarea>
<input type ="text" id="Autor1" placeholder="Autor einfügen"/>
<input id="Bewertung" type="text" placeholder="Bewertung von 1-10" />
<button id = "Einreichen">Einreichen </button>
<button id = "Löschen">Löschen</button>
</form>
Script:
<script>
document.getElementById("Add").innerHTML = "Add";
document.getElementById("Add").addEventListener("click",
function(e){
e.preventDefault();
if((document.getElementById("Autor1").value !== "" && document.getElementById("Quote1").value !== ""&& (document.getElementById("Rating"
).value > 1) && document.getElementById("Rating").value < 10)){
var table = document.getElementById("ZitatenOrdnung");
var 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.lastChild.nodeValue = ('"' + document.getElementById("Quote1").value + '"');
cell1.setAttribute('contentEditable', 'true');
cell2.innerHTML = ("~" + document.getElementById("Autor1").value);
cell3.innerHTML = (document.getElementById("Rating").value);
cell3.setAttribute('contentEditable', 'true');
cell3.style.textAlign = 'center';
The cells you've inserted are empty, they don't have childrens, so lastChild is undefined.
You may append a textNode instead:
cell1.appendChild(document.createTextNode('"' + document.getElementById("Zitat1").value + '"'));
There also isn't an element with the id Quote1 (I guess you mean Zitat1)
I am writing a code in HTML + Jquery and need to add rows to a table dynamically.
I've written the code to add the rows dynamically, but it doesn't seem to work.
Here is my JScript code :
<script language="JavaScript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "date";
element1.name="datebox[];
element1.id = "dt";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var element2 = document.createElement("input");
element2.type = "select";
element2.name = "selectbox[]";
element2.id = "slct";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
cell3.innerHTML = rowCount + 1;
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
element3.id = "txt";
cell3.appendChild(element3);
table.appendChild(cell1);
}
</script>
This is my Table:
<table id = "tab" style="width:500px">
<tr>
<th>Date</th>
<th>Treatment Goal</th>
<th>Comment</th>
</tr>
<tr>
<td><INPUT type="date" name="datebox[]" id = "dt"/></td>
<td>
<SELECT name="selectbox[]" id = "slct">
</SELECT>
</td>
<td><INPUT type="text" name="txtbox[]" id = "txt"/></td>
</tr>
</table>
I am calling the function in the onClick event of a button like this :
<input type="button" id="add" value="+" name="Add" onclick="addRow('tab')"/>
The html page doesn't respond to the click event and nothing happens.
Cannot understand what's going wrong.
Working Fiddle
The first problem is a syntax error on this line (you didn't close the double quote):
element1.name="datebox[];
^ missing "
The second problem is you are appending the cell to the table which is wrong, you should be appending the row:
table.appendChild(row);
^ changed to row from cell
You are missing a quotation mark on the line:
element1.name="datebox[];
after the name element.
I have a HTML table and i can add a new row to that table using javascript.
I want to call a javascript (Ajax) function using the onchange event for each of the cells on the table.
`
<script type="text/javascript" src="nextTest.js"></script>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHTML = rowCount + 1;
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
element2.onchange = nexttest();
cell2.appendChild(element2);
}
</SCRIPT>
</HEAD>
<body>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD> 1 </TD>
<TD> <INPUT type="text" /> </TD>
</TR>
</TABLE>
</body>
</html>`
When i press the button, a new row is added and the onchange event is fired.
What i want to do is when ever someone enters data into those new cells, i want the onchange event to fire. The event is called 'nextTest' and it is stored in an external file.
When i insert the new row, the event fires, but if i update one of the cells, nothing happens.
What am i doing wrong?
Thanks in advance
you must assign a function, not a function-call(except the called function returns another function).
Omit the parentheses:
element2.onchange = nexttest;
function nexttest(evt){
alert(evt.target.value);
}
function addRow (tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHTML = rowCount + 1;
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
element2.onchange = nexttest; // give a valid function identifier here .
cell2.appendChild(element2);
}
http://jsbin.com/iropam/2/edit