I am doing a basic course for web development. I used html for creating a very simple table with 2 columns: Apples and fruits. Fruits should be the number of apples + 5 (basic approach for a better comprehension). I tried to add an addeventlistener as well
var apples = document.getElementById('apples');
var fruits = document.getElementById('fruits');
function calculate() {
fruits = apples + 5;
fruits.innerHTML = fruits;
}
// Get all the input columns
var inputElement = document.getElementById('apples');
// Add Event Listeners to all the input columns
inputElement.addEventListener('change', calculate);
<table class="egt">
<tr>
<th>apples</th>
<th>fruits</th>
</tr>
<tr>
<td>
<input type="number" id="apples">
</td>
<td>
<input type="number" id="fruits">
</td>
</tr>
</table>
I don't get the "8" on the column "fruits". Am I missing something in the code? Thanks in advance
var fruits = document.getElementById('fruits');
function calculate(event) {
//use event here to get the apples element value on every change event.target.value so you dont have to fetch the element every time
fruits.value = (parseInt(event.target.value) + 5);
//parse it as nummber and + 5
}
var inputElement = document.getElementById('apples');
inputElement.addEventListener('change', calculate);
<table class="egt">
<tr>
<th>apples</th>
<th>fruits</th>
</tr>
<tr>
<td>
<input type="number" id="apples">
</td>
<td>
<input type="number" id="fruits">
</td>
</tr>
</table>
Read here how to target Event Property
And also read about JavaScript parseInt() Function
Input values are updated on value attribute on input tag. So it is needed to get value like fruits.value and apple.value.
And apples.value is string so for sum operation, it is needed to convert it to number.
var apples = document.getElementById('apples');
var fruits = document.getElementById('fruits');
function calculate() {
fruits.value = Number(apples.value) + 5;
}
// Get all the input columns
var inputElement = document.getElementById('apples');
// Add Event Listeners to all the input columns
inputElement.addEventListener('change', calculate);
<table class="egt">
<tr>
<th>apples</th>
<th>fruits</th>
</tr>
<tr>
<td>
<input type="number" id="apples">
</td>
<td>
<input type="number" id="fruits">
</td>
</tr>
</table>
Get the string value from apples.value and use parseInt to convert to an integer then update the fruits.
var apples = document.getElementById('apples');
var fruits = document.getElementById('fruits');
function calculate() {
fruits.value = parseInt(apples.value) + 5;
}
// Get all the input columns
var inputElement = document.getElementById('apples');
// Add Event Listeners to all the input columns
inputElement.addEventListener('change', calculate);
<table class="egt">
<tr>
<th>apples</th>
<th>fruits</th>
</tr>
<tr>
<td>
<input type="number" id="apples">
</td>
<td>
<input type="number" id="fruits">
</td>
</tr>
</table>
Related
I'm trying to create a new role but I want a row where there isn't any value in the textfield.
<form action="Fruits" method="Post" enctype="multipart/form-data">
<table id="myTable">
<c:forEach items="${fruits}" var="val" varStatus="count">
<thead>
<tr>
<th>Fruit</th>
<th>Color</th>
</thead>
<tbody>
<td><input type="text" name="name" id="name" value="${val.name}"></td>
<td><input type="text" name="color" id="color" value="${val.color}"></td>
</tbody>
</table>
<button type="button" class="btn btn-default json-editor-btn-add" onclick="myFunction()">Add</button>
</form>
For now whenever I create a new role, it gives me the values of the first row and fill the text field. Is there a way where I just create a row where it doesnt have any values.
function myFunction(){
var table = document.getElementById("myTable");
var first_tr = table.firstElementChild;
var second_tr = first_tr.nextElementSibling;
var tr_clone = first_tr.cloneNode(true);
var tb_clone = second_tr.cloneNode(true);
table.append(tr_clone);
table.append(tb_clone);
}
I'm expecting a blank field text for all of the column upon creating a row
Instead of cloning previous rows create a row template using a template/string literal that you can insert before the end of the tbody element.
Note: you don't have any rows in your current table's - you just have two cells. You also can't have multiple cells with the same id. Ids are supposed to be unique within a document. If you have to identify cells separately you should use a data attribute instead.
const rowTmpl = `<tr>
<td><input type="text" name="name"></td>
<td><input type="text" name="color"></td>
</tr>`;
const tbody = document.querySelector('tbody');
const button = document.querySelector('button');
button.addEventListener('click', handleClick);
function handleClick(e) {
tbody.insertAdjacentHTML('beforeend', rowTmpl);
}
<table>
<thead>
<tr><td>Fruit</td><td>Color</td></tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" value="Apple" name="name"></td>
<td>
<input type="text" value="Red" name="color">
</td>
</tr>
</tbody>
</table>
<button type="button">Add row</button>
Add below lines in your function.
let array_of_input = tb_clone.querySelectorAll('input');
array_of_input.forEach(cur => {
cur.value = '';
})
Your final function looks like this.
function myFunction() {
var table = document.getElementById("myTable");
var first_tr = table.firstElementChild;
var second_tr = first_tr.nextElementSibling;
var tr_clone = first_tr.cloneNode(true);
var tb_clone = second_tr.cloneNode(true);
table.append(tr_clone);
table.append(tb_clone);
let array_of_input = tb_clone.querySelectorAll('input');
array_of_input.forEach(cur => {
cur.value = '';
})
}
Great day Community,i'm facing clone whole table problem, if it have solution of clone several row it will be helping a lots.
If using document.getElementsByTagName("table")[2]; it can clone the table and put it in body because i'm using document.body.appendChild(myClone) to do it.
Here is some code:
Solution 1:
function myFunction() {
myTable = document.getElementsByTagName("table")[2]; // doesn't use any table id
myClone = myTable.cloneNode(true);
var y = document.body.appendChild(myClone);
}
Solution 2:
function myFunction() {
var x = document.getElementById("0"); // using this to find auto genereate id for table
test = x.cloneNode(true);
}
Html Display:
<table>
<tr>
<td>
<table id="0">
<tr>
<td><span></span>Name:<input type="text" value="Tom"/> </td>
<td><span> </span>Age:<input type="text" value="25"/> </td>
<td><span> </span>Email:<input type="text" value="tom#gmail.com"/> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table id="1">
<tr>
<td><span></span>Name:<input type="text" value="Alice"/> </td>
<td><span> </span>Age:<input type="text" value="22"/> </td>
<td><span> </span>Email:<input type="text" value="alice#gmail.com"/> </td>
</tr>
</table>
<input type="button" onclick="myFunction()"/>
</td>
</tr>
</table>
Expected result clone the table after the button, the table inside will not have more than 5.
Please help thank you.
Although Dominic Amal Joe F's answer was on the right track, it had some flaws, as well as the structure of the OP table. I think this code would work properly:
function myFunction(){
// get main table body
var tableBody = document.getElementById('mytable').children[0];
// get existing rows
var rows = tableBody.children.length;
// clone the last row (which contains the last table)
var newRow = tableBody.children[rows-1].cloneNode(true);
// get the new row table
var newTable = newRow.children[0].children[0]
// change the table id
newTable.setAttribute('id', rows);
// reset the inputs values
var cells = newTable.children[0].children[0].children;
for (var i=0; i<cells.length; i++) {
cells[i].children[1].value = "";
}
// append the new row to the main table body
tableBody.appendChild(newRow);
}
<table id="mytable">
<tr>
<td>
<table id="0">
<tr>
<td><span>Name:</span><input type="text" value="Tom"/></td>
<td><span>Age:</span><input type="number" value="25"/></td>
<td><span>Email:</span><input type="email" value="tom#gmail.com"/></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table id="1">
<tr>
<td><span>Name:</span><input type="text" value="Alice"/></td>
<td><span>Age:</span><input type="number" value="22"/></td>
<td><span>Email:</span><input type="email" value="alice#gmail.com"/></td>
</tr>
</table>
</td>
</tr>
</table>
<button onclick="myFunction()">Clone</button>
I feel the following code will help you.
HTML
<table>
<button onclick="myFunction()">clone</button>
<tr>
<table id="parent-table">
<tr id="parent-row">
<td><span></span>Name:<input type="text" value="Tom"/> </td>
<td><span> </span>Age:<input type="text" value="25"/> </td>
<td><span> </span>Email:<input type="text" value="tom#gmail.com"/></td>
</tr>
</table>
</tr>
</table>
JavaScript
function myFunction(){
let parentTable = document.getElementById("parent-table");
let parentRow = document.getElementsByTagName('tr')
let clone = parentRow[1].cloneNode(true);
parentTable.appendChild(clone)
}
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:)
I want to duplicate the second <tr> everytime I click button add, as it shows in here, I mean I want to whenever I click on the button add a new <tr> will be added that do the same thing as the previous one.
<form id="frm1" action="Calculate.html">
<table id= "myTable">
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
</tr>
<tr id= "rowToClone">
<td>
<select id= "products">
<option value="80">Product-A</option>
<option value="80">Product-B</option>
<option value="80">Product-C</option>
<option value="80">Product-D</option>
<option value="16">Product-E</option>
</select>
</td>
<td><input type="number" id="ndc" placeholder=""></td>
<td><p id="ndpc"></p></td>
<td><p id="pu"></p></td>
<td><p id="ptpp"></p></td>
</tr>
</table>
<input type="button" onclick="Calculate()" value="calculate">
<input type="button" onclick="AddSelect()" value="Add">
I want it to do the same whole thing, I tried but never got successful the second part I am stuck to
first part:
function Calculate() {
var e = document.getElementById("products");
var productValue = e.options[e.selectedIndex].value;
document.getElementById("ndpc").innerHTML = productValue;
document.getElementById("ndpc").value = productValue;
if (e.selectedIndex === 0){
document.getElementById("pu").value = 21.2;
}
else if (e.selectedIndex === 1) {
document.getElementById("pu").value = 25.7;
}
else if (e.selectedIndex === 2 || e.selectedIndex === 3 ) {
document.getElementById("pu").value = 14;
}
else {
document.getElementById("pu").value = 6;
}
var pu = document.getElementById("pu").value;
document.getElementById("pu").innerHTML = pu;
var ndc = document.getElementById("ndc").value;
var ndpc = document.getElementById("ndpc").value;
var Result = ndc * ndpc * pu;
document.getElementById("ptpp").innerHTML = Result;
};
the second part that I want to solve:
function AddSelect(){
var row = document.getElementbyId("rowToClone");
var table = document.getElementById("myTable");
var clone = row.cloneNode(true);
clone.id = "New";
function createRow() {
//I don't know what to do.
} };
I am new to Javascript obviously, please help me.
When using methods such as cloneNode(), or createElement() you'll need to append the new node to the DOM or it'll just float around aimlessly. Also, when cloning a node, keep in mind that if it and/or its children have any #ids, you'll end up having duplicated #ids which is super invalid. You should either change the #ids on all clones or do away with #ids on cloned nodes and use classes, tags, attributes, etc. instead.
In this demo, I replaced the form controls' #ids with name attribute since that's all you need to have in order to submit values from a <form> to a server (that and a <input type='submit'> button of course).
Demo
function addSelect() {
var T = document.getElementById('xTable');
var R = document.querySelectorAll('tbody .row')[0];
var C = R.cloneNode(true);
T.appendChild(C);
}
<form id="frm1" action="Calculate.html">
<table id="xTable">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
</tr>
</thead>
<tr class="row">
<td>
<select name="products">
<option value="80">Product-A</option>
<option value="80">Product-B</option>
<option value="80">Product-C</option>
<option value="80">Product-D</option>
<option value="16">Product-E</option>
</select>
</td>
<td><input type="number" name="ndc" placeholder=""></td>
<td>
<p id="ndpc"></p>
</td>
<td>
<p id="pu"></p>
</td>
<td>
<p id="ptpp"></p>
</td>
</tr>
</table>
<input type="button" onclick="addSelect()" value="Add">
</form>
1)here i'm doing clone of a row...but this code is working only in eclipse [ ie ,cloning is working ] and it is also not working in any browsers.
2)What is the solution to get the values of text boxes in the cloned rows having same name, and insert into the database using jsp and servlet?
how can i get those values with same name
3)i have servlet code to get only single value from jsp
String address_seq_num =request.getParameter("address_seq_num");
how can i get the value of address seq number in the cloned row fromjsp to servlet to insert into the next row of a table in the database.
4)if i mention "DOCUMENT TYPE" to this code ,it will not work in eclipse also.....
please guide me...
JavaScript
function clonetable() {
var x=document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
var row = document.getElementById("table_row_clone"); // find row to copy
var table = document.getElementById("table_body"); // find table to append to
var clone = row.cloneNode(true); // copy children too
var tb1 = clone.document.getElementById("asn");//here i'm incrementing the value
tb1.value=rowCount+1;//of "address seq num " in the cloned row
clone.id = "abc"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
function deltable() {
var x = document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
if (rowCount > 1) {
x.deleteRow(rowCount - 1);
} //delete the last row
}
HTML
<table id="main_table" align="center" style="width:75%">
<tbody id="table_body">
<tr id="table_row_clone">
<td>
<table align="center" style="width:100%">
<tr>
<td align="center">
<div style="border:3px solid silver;border-radius:5px;background-color:grey">
<table width="100%">
<tr>
<th align="center">Address Details</th>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div style="border:3px solid silver;border-radius:5px;background-color:#1E90FF">
<table align="center" style="width:99%">
<tr style="background-color:#1E90FF">
<td style="width:35%">
<table width="100%">
<tr id="slrow">
<td style="width:43%">Address Seq Num</td>
<td>
<input id="asn" style="width:60px" name="address_seq_num" type="text" value="1" readonly>
</td>
</tr>
</table>
</td>
<td width="49%" align="right">
<input style="width:80%" type="text" value="Reg.office/Primary Office">
</td>
<td align="right">
<input style="width:30px" type="button" value="+" onclick="clonetable()">
<input style="width:30px" type="button" value="-" onclick="deltable()">
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
</tbody>
Per your HTML (which is messy, by the way) you can increment that textbox's value with something like:
var tb = document.getElementById("asn");
tb.value = parseInt(tb.value, 10) + 1;
The trick is you have to cast the textbox's value into a number, which is what parseInt is doing in that example.
Note that the above snippet will give you "NaN" in the textbox if the value is not a valid number - it's not doing any data validation at all.