Add/delete row from a table - javascript

I have this table with some dependents information and there is a add and delete button for each row to add/delete additional dependents. When I click "add" button, a new row gets added to the table, but when I click the "delete" button, it deletes the header row first and then on subsequent clicking, it deletes the corresponding row.
Here is what I have:
Javascript code
function deleteRow(row){
var d = row.parentNode.parentNode.rowIndex;
document.getElementById('dsTable').deleteRow(d);
}
HTML code
<table id = 'dsTable' >
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(this)" </td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(this)" </td>
</tr>
</table>

JavaScript with a few modifications:
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
And the HTML with a little difference:
<table id="dsTable">
<tbody>
<tr>
<td>Relationship Type</td>
<td>Date of Birth</td>
<td>Gender</td>
</tr>
<tr>
<td>Spouse</td>
<td>1980-22-03</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
<tr>
<td>Child</td>
<td>2008-23-06</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
</tbody>
</table>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

jQuery has a nice function for removing elements from the DOM.
The closest() function is cool because it will "get the first element that matches the selector by testing the element itself and traversing up through its ancestors."
$(this).closest("tr").remove();
Each delete button could run that very succinct code with a function call.

Lots of good answers, but here is one more ;)
You can add handler for the click to the table
<table id = 'dsTable' onclick="tableclick(event)">
And then just find out what the target of the event was
function tableclick(e) {
if(!e)
e = window.event;
if(e.target.value == "Delete")
deleteRow( e.target.parentNode.parentNode.rowIndex );
}
Then you don't have to add event handlers for each row and your html looks neater. If you don't want any javascript in your html you can even add the handler when page loads:
document.getElementById('dsTable').addEventListener('click',tableclick,false);
​​
Here is working code: http://jsfiddle.net/hX4f4/2/

I would try formatting your table correctly first off like so:
I cannot help but thinking that formatting the table could at the very least not do any harm.
<table>
<thead>
<th>Header1</th>
......
</thead>
<tbody>
<tr><td>Content1</td>....</tr>
......
</tbody>
</table>

Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.

I suggest using jQuery. What you are doing right now is easy to achieve without jQuery, but as you will want new features and more functionality, jQuery will save you a lot of time. I would also like to mention that you shouldn't have multiple DOM elements with the same ID in one document. In such case use class attribute.
html:
<table id="dsTable">
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
</table>
javascript:
$('body').on('click', 'input.deleteDep', function() {
$(this).parents('tr').remove();
});
Remember that you need to reference jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Here a working jsfiddle example:
http://jsfiddle.net/p9dey/1/

Use the following code to delete the particular row of table
<td>
<asp:ImageButton ID="imgDeleteAction" runat="server" ImageUrl="~/Images/trash.png" OnClientClick="DeleteRow(this);return false;"/>
</td>
function DeleteRow(element) {
document.getElementById("tableID").deleteRow(element.parentNode.parentNode.rowIndex);
}

try this for insert
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
and this for delete
document.getElementById("myTable").deleteRow(0);

Yeah It is working great
but i have to delete from localstorage too, when user click button , here is my code
function RemoveRow(id) {
// event.target will be the input element.
// console.log(id)
let td1 = event.target.parentNode;
let tr1 = td1.parentNode;
tr1.parentNode.removeChild(tr1);// the row to be removed
// const books = JSON.parse(localStorage.getItem("books"));
// const newBooks= books.filter(book=> book.id !== books.id);
// console.log(books, newBooks)
// localStorage.setItem("books", JSON.stringify(newBooks));
}
// function RemoveRow(btn) {
// var row = btn.parentNode.parentNode;
// row.parentNode.removeChild(row);
// }
button tag
class Display {
add(book) {
console.log('Adding to UI');
let tableBody = document.getElementById('tableBody')
let uiString = `<tr class="tableBody" id="tableBody" data-id="${book.id}">
<td id="search">${book.name}</td>
<td>${book.author}</td>
<td>${book.type}</td>
<td><input type="button" value="Delete Row" class="btn btn-outline-danger" onclick="RemoveRow(this)"></td>
</tr>`;
tableBody.innerHTML += uiString;
// save the data to the browser's local storage -----
const books = JSON.parse(localStorage.getItem("books"));
// console.log(books);
if (!books.some((oldBook) => oldBook.id === book.id)) books.push(book);
localStorage.setItem("books", JSON.stringify(books));
}

Hi I would do something like this:
var id = 4; // inital number of rows plus one
function addRow(){
// add a new tr with id
// increment id;
}
function deleteRow(id){
$("#" + id).remove();
}
and i would have a table like this:
<table id = 'dsTable' >
<tr id=1>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr id=2>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)" </td>
</tr>
<tr id=3>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)" </td>
</tr>
</table>
Also if you want you can make a loop to build up the table. So it will be easy to build the table. The same you can do with edit:)

Related

Update td content of a loaded tr

I tried several stuff I found now, but nothing seems to work for me.
On my site I got two tables. In one of them are entries with a button in the last column "add" which deletes the row from that table and moves it to the other table. When this happens I want to edit the content of that last <td>, so that there will be an "delete" button, which moves the entry back to the first table.
$("#questiontable").on('click', '.btnDelete', function () {
var question_id = $(this).val();
var tr = $(this).closest('tr').remove().clone();
tr[4].html("<button>delete</button>");
tr.appendTo("#currentquestiontable");
});
The td looks like this before:
<td>
<input type="hidden" name="id" value= {{question.id}} />
<button class="btnDelete">Hinzufügen</button>
</td>
You can set one click listener for both tables , and check by table id in order to transfer tr from table to another , same thing for text button ,(only change innerText button)
use listner for both table selectors :
$("#questiontable , #currentquestiontable").on('click', '.btnAction', function() {
var question_id = $(this).prev("input").val();
console.log(question_id)
let id = $(this).closest('table').attr("id");
var $tr = $(this).closest('tr').remove().clone();
let tableId= "";
let buttonText = "";
if(id === "questiontable") {
tableId= "#currentquestiontable";
buttonText = "remove";
}
else {
tableId= "#questiontable";
buttonText = "add";
}
$tr.find(".btnAction").text(buttonText);
$tr.appendTo(tableId);
});
See below example :
$("#questiontable , #currentquestiontable").on('click', '.btnAction', function() {
var question_id = $(this).prev("input").val();
console.log(question_id)
let id = $(this).closest('table').attr("id");
var $tr = $(this).closest('tr').remove().clone();
let tableId= "";
let buttonText = "";
if(id === "questiontable") {
tableId= "#currentquestiontable";
buttonText = "remove";
}
else {
tableId= "#questiontable";
buttonText = "add";
}
$tr.find(".btnAction").text(buttonText);
$tr.appendTo(tableId);
});
#currentquestiontable {
background-color:gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
table 1
<table id="currentquestiontable">
<tr>
<td>id</td>
<td>name</td>
<td>action</td>
</tr>
</table>
<hr>
<table id="questiontable">
<tr>
<td>id</td>
<td>name</td>
<td>action</td>
</tr>
<tr>
<td>1</td>
<td>elemnt n° 1</td>
<td>
<input type="hidden" name="id" value="1" />
<button class="btnAction">add</button>
</td>
</tr>
<tr>
<td>2</td>
<td>elemnt n° 2</td>
<td>
<input type="hidden" name="id" value="2" />
<button class="btnAction">add</button>
</td>
</tr>
<tr>
<td>3</td>
<td>elemnt n° 3</td>
<td>
<input type="hidden" name="id" value="3" />
<button class="btnAction">add</button>
</td>
</tr>
<tr>
<td>4</td>
<td>elemnt n° 4</td>
<td>
<input type="hidden" name="id" value="4" />
<button class="btnAction">add</button>
</td>
</tr>
<tr>
<td>5</td>
<td>elemnt n° 5</td>
<td>
<input type="hidden" name="id" value="5" />
<button class="btnAction">add</button>
</td>
</tr>
</table>

How to set input text value from table data on click of that row in javascript

I have a jsp page where i am displaying value from data base .
Now i need to edit the table value in click of that particular row and that selected row value should get set into respective input text .
My java script function is getting called but clicked value is not getting displayed into respective input type .
The java script function name is onRowClick
I am adding code for that .
Please suggest .
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script>
function onRowClick(){
var table = document.getElementById("hoteltable"),rIndex;
for(var i = 0; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
rIndex = this.rowIndex;
document.getElementByName("hId").value = this.cells[0].innerHTML;
document.getElementByName("hName").value = this.cells[1].innerHTML;
document.getElementByName("hArea").value = this.cells[2].innerHTML;
document.getElementByName("hNumOfRooms").value = this.cells[3].innerHTML;
document.getElementByName("hImgUrl").value = this.cells[4].innerHTML;
hideButton();
showDelete();
showEdit();
};
}
}
</script>
</head>
<body>
<h2>Welcome to Admin Page</h2>
<div id="sub-left">
<form:form action="hotelaction" method="post" modelAttribute="hotel">
<table>
<tr>
<td>hotelId</td>
<td><form:input name="hId" path="hotelId"></form:input></td>
<td><form:errors path="hotelId" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>hotelName:</td>
<td><form:input name="hName" path="hotelName"></form:input></td>
<td><form:errors path="hotelName" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>hotelArea:</td>
<td><form:select name="hArea" path="hotelArea">
<form:option value="Marthalli">Marathalli</form:option>
<form:option value="SilkBoard">SilkBoard</form:option>
</form:select></td>
<td><form:errors path="hotelArea" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>hotelNumberOfRooms:</td>
<td><form:input name="hNumOfRooms" path="hotelNumOfRooms"></form:input></td>
<td><form:errors path="hotelNumOfRooms" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>hotelImgUrl:</td>
<td><form:input name="hImgUrl" path="hotelImgUrl"></form:input></td>
<td><form:errors path="hotelImgUrl" cssClass="error"></form:errors></td>
</tr>
</table>
<div id="sub-right">
<input type="submit" value="Add" name="action" id="btn1" class="glass2"></input> <br> <br>
<input type="submit"value="Edit" name="action" id="btn2" class="glass2" /><br> <br>
<input type="submit" value="Delete" name="action" id="btn3" class="glass2"></input><br> <br>
<input type="reset"value="Reset" name="reset" onClick=showButton(); class="glass2" />
</div>
</form:form>
</div>
<div class="myTable">
<table id="hoteltable" border="1" width=100%>
<tr>
<td><h4>hotelId</h4></td>
<td><h4>hotelName</h4></td>
<td><h4>hotelArea</h4></td>
<td><h4>hotelNumOfRooms</h4></td>
<td><h4>hotelImageUrl</h4></td>
</tr>
<c:forEach var="hotels" items="${hotelList}">
<tr onclick="onRowClick()">
<td >${hotels.hotelId}</td>
<td>${hotels.hotelName}</td>
<td>${hotels.hotelArea}</td>
<td>${hotels.hotelNumOfRooms}</td>
<td>${hotels.hotelImgUrl}</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
If you look in the web console, you'll find an error message. There is no document.getElementByName function in the DOM. There's getElementsByName (plural), but not a singular, and that one wouldn't really help you since it would give you a collection of all of the elements with that name, anywhere on the page. (Although if the only ones with those names are the ones you want, you could use it and then use [0] to get the only entry in the resulting collection.)
There's a different problem, though: Your click="onRowClick()" doesn't pass on any information about which row was clicked, and the function itself just hooks up event handlers on the rows rather than actually doing what you want done on click.
Instead, hook click on the table, and check to see if the click passed throug a row; if it did, fill in the information in the first table. See comments:
// Hook click on the table, rather than individual rows
document.getElementById("hoteltable").addEventListener("click", function(e) {
// Make sure the click passed through a row in this table
var row = e.target.closest("tr");
if (!row || !this.contains(row)) {
return;
}
// Get the form we're filling in
var form = document.querySelector("form[action=hotelaction]");
// Fill in the various inputs
// Note: I'd recommend giving each cell a data-name attribute or something
// and using those rather than using `row.cells[0]` and such. That way
// when (not if ;-) ) you change the source table, the cell references
// aren't messed up
form.querySelector("[name=hId]").value = row.cells[0].innerHTML;
form.querySelector("[name=hName]").value = row.cells[1].innerHTML;
form.querySelector("[name=hArea]").value = row.cells[2].innerHTML;
form.querySelector("[name=hNumOfRooms]").value = row.cells[3].innerHTML;
form.querySelector("[name=hImgUrl]").value = row.cells[4].innerHTML;
/*
hideButton();
showDelete();
showEdit();
*/
});
<h2>Welcome to Admin Page</h2>
<div id="sub-left">
<form action="hotelaction" method="post" modelAttribute="hotel">
<table>
<tr>
<td>hotelId</td>
<td>
<input name="hId" path="hotelId">
</td>
<td>
<span class="error"></span>
</td>
</tr>
<tr>
<td>hotelName:</td>
<td>
<input name="hName" path="hotelName">
</td>
<td>
<span class="error"></span>
</td>
</tr>
<tr>
<td>hotelArea:</td>
<td>
<select name="hArea" path="hotelArea">
<option value="Marthalli">Marathalli</option>
<option value="SilkBoard">SilkBoard</option>
</select>
</td>
<td>
<span class="error"></span>
</td>
</tr>
<tr>
<td>hotelNumberOfRooms:</td>
<td>
<input name="hNumOfRooms" path="hotelNumOfRooms">
</td>
<td>
<span class="error"></span>
</td>
</tr>
<tr>
<td>hotelImgUrl:</td>
<td>
<input name="hImgUrl" path="hotelImgUrl">
</td>
<td>
<span class="error"></span>
</td>
</tr>
</table>
<div id="sub-right">
<input type="submit" value="Add" name="action" id="btn1" class="glass2"><br> <br>
<input type="submit" value="Edit" name="action" id="btn2" class="glass2" /><br> <br>
<input type="submit" value="Delete" name="action" id="btn3" class="glass2"><br> <br>
<input type="reset" value="Reset" name="reset" onClick=showButton(); class="glass2" />
</div>
</form>
</div>
<div class="myTable">
<table id="hoteltable" border="1" width=100%>
<tr>
<td>
<h4>hotelId</h4>
</td>
<td>
<h4>hotelName</h4>
</td>
<td>
<h4>hotelArea</h4>
</td>
<td>
<h4>hotelNumOfRooms</h4>
</td>
<td>
<h4>hotelImageUrl</h4>
</td>
</tr>
<tr>
<td>1</td>
<td>Savoy</td>
<td>Marthalli</td>
<td>300</td>
<td>https://via.placeholder.com/150?text=Savoy</td>
</tr>
<tr>
<td>2</td>
<td>Marriott</td>
<td>SilkBoard</td>
<td>450</td>
<td>https://via.placeholder.com/150?text=Marriott</td>
</tr>
<tr>
<td>3</td>
<td>Premier Inn</td>
<td>Marthalli</td>
<td>150</td>
<td>https://via.placeholder.com/150?text=Premier+Inn</td>
</tr>
</table>
</div>
Note that I removed from JSP- or template-isms from the HTML in that, so it used standard form inputs. I assume what gets delivered to the browser uses standard form elements.

jQuery Remove by id

I am adding test in a fieldset and while I can add them, I am unsure how to write the correct function to remove them. I had it working in javascript but was asked to write it using JQuery and cannot seem to make it work. All example I have researched don't seem to work with my original cloning function which builds a remove button in it. The fieldsets also duplicate and I have the code working for that already, just need a little help with this remove event function.
Here it the javascript/jquery:
document.getElementById('button').onclick = duplicate;
var i = 0;
var original = document.getElementById('dataTes');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "dataTes" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
function remove(){
}
Here is the html :
<fieldset>
<legend>Test</legend>
<input type="submit" class="button" id = "button" value="+" onlick="duplicate()" title = "#">
<input type="submit" class="button" id = "button" value="-" onlick="remove()" title = "#">
<div id="dataTes">
<table align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-top:10px;" width="97%">
<tr>
<td width="100px">Test</td>
<td width="2px">:</td>
<td width="2px"><input type="text" name="usrname"></td>
<td>
<input type="submit" class="button" id = "add" value="+" onClick="addRow('#')" title = "#">
<input type="submit" class="button" id = "add" value="-" onClick="deleteRow('#')" title = "#">
</td>
</tr>
<table align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-top:5px;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill</td>
<td width="2px">:</td>
<td><input type="text" name="usrname"></td>
</tr>
<tr>
<td width="2px"></td>
<td width="100px">Fill</td>
<td width="2px">:</td>
<td><input type="text" name="usrname"></td>
</tr>
<table id="dataID" align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
</table>
</table>
</table>
</div>
</fieldset>
Here is the quick and complete solution. Remove your inline functions to elements add and remove buttons and attach event to their id as below:
var id = 0; //global id to create unique id
$(document).ready(function() {
//attach click event to element/button with id add and remove
$("#add,#remove").on('click', function() {
var currentElemID = $(this).attr('id'); //get the element clicked
if (currentElemID == "add") { //if it is add elem
var cloneParent = $("#dataTes").clone(); //clone the dataTes element
id=$("div[id^=dataTes]").length;//get the count of dataTes element
//it will be always more than last count each time
cloneParent.find('[id]').each(function() {
//loop through each element which has id attribute in cloned set and replace them
//with incremented value
var $el = $(this); //get the element
$el.attr('id', $el.attr('id') + id);
//ids would now be add1,add2 etc.,
});
cloneParent.attr('id', cloneParent.attr('id') + id);//replace cloneParent id
cloneParent.appendTo('fieldset');//append the element to fieldset
$("#remove").show();//show remove button only if there is more than one dataTes element
} else {
$("div[id^=dataTes]:last").remove();
//just remove the last dataTes
//[id^=dataTes]:last annotates remove last div whose id begins with dataTes
//remember we have id like dataTes1,dataTes2 etc
if($("div[id^=dataTes]").length==1){
//check if only one element is present
$("#remove").hide();//if yes hide the remove button
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset>
<legend>Test</legend>
<input type="submit" class="button" id="add" value="+" title="#">
<input type="submit" class="button" id="remove" value="-" style="display:none;" title="#">
<!--hide the remove button with display:none initially-->
<div id="dataTes">
<table align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-top:10px;" width="97%">
<tr>
<td width="100px">Test</td>
<td width="2px">:</td>
<td width="2px">
<input type="text" name="usrname">
</td>
<td>
<input type="submit" class="button" id="add" value="+" title="#">
<input type="submit" class="button" id="sub" value="-" title="#">
</td>
</tr>
<table align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-top:5px;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
<tr>
<td width="2px"></td>
<td width="100px">Fill</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
<table id="dataID" align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
</table>
</table>
</table>
</div>
</fieldset>
Explained line by line as comments. Do let me know if this confuses you.
1) Rename the duplicate IDs on the buttons (originally both id="button").
<input type="submit" class="button" id = "button_duplicate" value="+" onlick="duplicate()" title = "#">
<input type="submit" class="button" id = "button_remove" value="-" onlick="remove()" title = "#">
2) Bind the duplicate() and remove() functions on correct buttons. Instead of the document.getElementById('button').onclick = duplicate;
$("#button_duplicate").click(function(){
duplicate();
});
$("#button_remove").click(function(){
remove();
});
3) The remove function:
function remove(){
if($("#dataTes" + i).length > 0){
$("#dataTes" + i).remove();
i--;
}
}
value of i will be in the context. So you can get the id of the element and remove it. Then decrement i. Try this:
EDIT(corrected code):
function remove(){
var elId = "dataTes" + i;
var element = document.getElementById(elId);
element.parentNode.removeChild(element);
i--;
}
also first, you need to change id of the button in your html code.
<input type="submit" class="button1" id = "add" value="-" onClick="deleteRow('#')" title = "#">
and in javascript, it should be:
document.getElementById('button').onclick = duplicate;
document.getElementById('button1').onclick = remove;

How to delete table row by using both row id and table id in javascript?

<table id = 'dsTable' >
<tr id=1>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr id=2>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)" </td>
</tr>
<tr id=3>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)" </td>
</tr>
</table>
I want to delete the row by using both table id and row id in javascript. javascript code looks like this:
var child = document.getElementById(rowid);
child.parentNode.removeChild(child);
Here I am facing problem, the jsp page having multiple tables. So if I am trying to delete the row,it is deleting the other table rows. If I specify the table id along with row id the code will work fine.
Ids are suppose to be unique across your DOM, but you can first get the table
var table = document.getElementById("tableid");
var row = table.querySelector("tr[id='rowid']");
I recommend to use a different attribute other than id something like data-id
Now delete the row as
row.parentNode.removeChild(row)
var table = document.getElementById("dsTable");
var row = table.querySelector("tr[data-id='1']");
row.parentElement.removeChild(row);
<table id = 'dsTable' >
<tr data-id="1">
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr data-id="2">
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)" </td>
</tr>
<tr data-id="3">
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)" </td>
</tr>
</table>

How to get the data from a html table with multiple inputs [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a page containing this table which comes from a PHP script.
What I want to to do? I want to fetch every value inside these 4 inputs, separately and save them inside 4 Javascript variables. I already have the onclick="fetchGrades(); on every button.
How can I achieve this? It's the last thing I need to do on this project.
Also, I'm using all these technologies: PHP, MySQL, jQuery, Bootstrap, AJAX
As requested, the HTML of the current table:
<table class="table table-striped">
<thead>
<tr>
<th>61</th>
<th>1º </th>
<th>2º </th>
<th>3º </th>
<th>4º </th>
<th> Botão </th>
</tr>
</thead>
<tbody>
<tr>
<td>Patrick Maia</td>
<td><input id="e12467" type="text"> </td>
<td><input id="e12467" type="text"> </td>
<td><input id="e12467" type="text"> </td>
<td><input id="e12467" type="text"> </td>
<td><button class="btn btn-primary" onclick="fetchGrades();"> Adicionar </button></td>
</tr>
<tr>
<td>Rodrigo Marques</td>
<td><input id="46c9ac" type="text"> </td>
<td><input id="46c9ac" type="text"> </td>
<td><input id="46c9ac" type="text"> </td>
<td><input id="46c9ac" type="text"> </td>
<td><button class="btn btn-primary" onclick="fetchGrades();"> Adicionar </button></td>
</tr>
</tbody>
</table>
The ID's inside every input comes from a field on the MySQL they come from.
If your inputs in your HTML table were organized something like this:
<table>
<tr>
<th>
61
</th>
<th>
1
</th>
<th>
2
</th>
<th>
3
</th>
<th>
4
</th>
<th>
Boton
</th>
</tr>
<tr>
<td>
Patrick Maia
</td>
<td>
<input class="tblData_Row_1" type="text" />
</td>
<td>
<input class="tblData_Row_1" type="text" />
</td>
<td>
<input class="tblData_Row_1" type="text" />
</td>
<td>
<input class="tblData_Row_1" type="text" />
</td>
<td>
<input id="Button1" type="button" value="Accionar" onclick="fetchGrades('tblData_Row_1');" />
</td>
</tr>
<tr>
<td>
Rodrigo Marquez
</td>
<td>
<input class="tblData_Row_2" type="text" />
</td>
<td>
<input class="tblData_Row_2" type="text" />
</td>
<td>
<input class="tblData_Row_2" type="text" />
</td>
<td>
<input class="tblData_Row_2" type="text" />
</td>
<td>
<input id="Button2" type="button" value="Accionar" onclick="fetchGrades('tblData_Row_2');" />
</td>
</tr>
</table>
You could easily use JQuery to handle the rest:
function fetchGrades(rowClass) {
var JSONresults = {};
var indexColumn = 0;
$('.' + rowClass).each(function () {
indexColumn++;
JSONresults['field_' + indexColumn] = $(this).val();
});
alert(JSON.stringify(JSONresults)); //show me my JSON object in string format
}
Try something like this ...
function fetchGrades() {
var first = document.getElementById('FirstField_row1').value;
var second = document.getElementById('SecondField_row1').value;
var third = document.getElementById('ThirdField_row1').value;
var fourth = document.getElementById('FourthField_row1').value;
}
WITH jQuery:
function fetchGrades() {
var first = $('#FirstField_row1').val();
var second = $('#SecondField_row1').val();
var third = $('#ThirdField_row1').val();
var fourth = $('#FourthField_row1').val();
}
ASSUMES:
<td><input id='FirstField_row1'/></td>
<td><input id='SecondField_row1'/></td>
<td><input id='ThirdField_row1'/></td>
<td><input id='FourthField_row1'/></td>
As the comments said, is tough to work without code. :-)
That said, the general answer is that you want to flag each row in some way so that your onClick script knows which row the button is referring to.
A simple example: each button passes a row number parameter when its onClick is triggered.
I hope that helps!
This finds the button that was pressed, navigates to the parent tr and then finds the first, second, etc. input elements and saves them into variables:
function fetchGrades(event) {
var sender = (event && event.target) || (window.event && window.event.srcElement);
var first = $(sender).closest('tr').find('input:eq(0)').val();
var second = $(sender).closest('tr').find('input:eq(1)').val();
var third = $(sender).closest('tr').find('input:eq(2)').val();
var fourth = $(sender).closest('tr').find('input:eq(3)').val();
}

Categories

Resources