Click on Add auto number incerment 1,2,3----- - javascript

HTML:
<table>
<tr>
<th><b>ADD</b></th>
<tr><td class = "tdCustom" ><apex:commandButton value="Add" action="{!addBatch}" id="update" </td></tr>
<td class = "tdCustom" style="width:100px;">
<apex:repeat value="{!batchMap[qliRow]}" var="child" id="therepeat2">
<table class="table-data" border = "1">
<apex:variable value="{!1}" var="batchrowNum"/>
<tr id="tr_clone">
<td> <apex:input value="0" id="counter"/></td>
<td>
<apex:commandButton value="Delete" action="{!deleteBatch}" />
</td></tr>
<apex:variable var="batchrowNum" value="{!batchrowNum+ 1}"/>
</table>
</apex:repeat>
</td>
</tr>
<apex:variable var="rowNum" value="{!rowNum + 1}"/>
</apex:repeat>
</apex:repeat>
</table>
Sample script:i tried
<script>
var val;
$("#update").click(function()
{
val = $('#counter').val();
val++;
$('#counter').prop('value',val )
});
</script>
I have one table "main table" and "sub table"(table inside maintable) while clicking on action="{!addBatch}" it is adding row on sub table.
If i have three items in main table i can see three add buttons .whatever add button i clicked it has to increment one number in <apex:input value="0" id="counter"/>
In the same when i deleting some child row in middle it has to rearrange number <apex:input value="0" id="counter"/>

Related

Clone table and display after button

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)
}

Increment the id of html field [duplicate]

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:)

Undefined when retrieving text from element

I have this code
<tr><td id="name">TEXT 1</td>
<td><input type="button" class="button_add" value="Add" ></td></tr>
<tr><td id="name">TEXT 2</td>
<td><input type="button" class="button_add" value="Add" ></td></tr>
I would to click on the button to read the value of the current element td. For eg.: "This is your text: TEXT1"-
My code in jQuery is :
$('.button_add').click(function() {
var name = $(this).attr("#name").html();
alert('This is your text' + name);
});
But when I click on the button I get the following error:
TypeError: $(...).attr(...) is undefined
And it doesn't work. What am I missing?
ID of an element must be unique, so use name as a class instead of as ID.
Since you need the value of td in the same tr, use .closest to find the tr then use the class selector to find the td
$('.button_add').click(function() {
var name = $(this).closest("tr").find('td.name').html();
//or since the target td is the previous sibling of the button's parent element
// var name = $(this).parent().prev().html();
alert('This is your text' + name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td class="name">TEXT 1</td>
<td>
<input type="button" class="button_add" value="Add">
</td>
</tr>
<tr>
<td class="name">TEXT 2</td>
<td>
<input type="button" class="button_add" value="Add">
</td>
</tr>
</table>

select dynamically muiltiple element from a html table

I want to select value from a dynamically list coming from database with javascript. My table <td> and <tr> are create dynamically from a database. I manage the "id" attribute with 0, 1 in front of its with a for loops. Also like "id" of the select's button
<tr>
<td id="pres0">Bear</td>
<td id="cod0">ddfd</td>
<td id="id0">23</td>
<td><input type="button" value="select" id="id-but-select0"></td>
</tr>
<tr>
<td id="pres1">Cat</td>
<td id="cod1">AZ</td>
<td id="id1">121</td>
<td><input type="button" value="select" id="id-but-select1"></td>
</tr>
<!-- the total count of the select of the database -->
<input id="nbra" type="hidden" value="2">
What i want is that when i put on the select button, i have an alert which show the value of the id of each td in javascript or jquery
I'd suggest:
function showCellValues(e) {
// preventing any default actions:
e.preventDefault();
// caching the 'this' for later use (potentially):
var self = this,
// creating a variable to traverse the DOM (in the while loop to follow):
cell = self,
// working out whether we need to use textContent or innerText to retrieve
// a node's text:
textProp = 'textContent' in document ? 'textContent' : 'innerText';
// while the cell element is not a <td> element:
while (cell.tagName.toLowerCase() !== 'td') {
// we assign the current parentNode to the cell variable,
// and then go again:
cell = cell.parentNode;
}
// an empty array to hold the key-value pairs:
var keyValues = [];
// converting the NodeList of the parentNode's child elements to an Array,
// iterating over that array with Array.prototype.forEach():
[].slice.call(cell.parentNode.children, 0).forEach(function (el) {
// we only want to get values from the siblings (not the cell
// containing the clicked <input />:
if (el !== cell) {
// if the cell is not the current el, we push a string
// to the keyValues array:
keyValues.push(el.id + ': ' + el[textProp]);
}
});
// showing the output; use alert, or return or whatever here to your
// requirements:
console.log(keyValues.join(', '));
}
// converting the NodeList of all inputs of type=button *and* value=select that
// are within a <td> element into an array, and iterating over that array:
[].slice.call(document.querySelectorAll('td > input[type="button"][value="select"]'), 0).forEach(function(button){
// binding the 'click' event-handler function (showCellValues):
button.addEventListener('click', showCellValues);
});
function showCellValues(e) {
e.preventDefault();
var self = this,
cell = self,
textProp = 'textContent' in document ? 'textContent' : 'innerText';
while (cell.tagName.toLowerCase() !== 'td') {
cell = cell.parentNode;
}
var keyValues = [];
[].slice.call(cell.parentNode.children, 0).forEach(function (el) {
if (el !== cell) {
keyValues.push(el.id + ': ' + el[textProp]);
}
});
console.log(keyValues.join(', '));
}
[].slice.call(document.querySelectorAll('td > input[type="button"][value="select"]'), 0).forEach(function(button){
button.addEventListener('click', showCellValues);
});
<table>
<tbody>
<tr>
<td id="pres0">Bear</td>
<td id="cod0">ddfd</td>
<td id="id0">23</td>
<td>
<input type="button" value="select" id="id-but-select0" />
</td>
</tr>
<tr>
<td id="pres1">Cat</td>
<td id="cod1">AZ</td>
<td id="id1">121</td>
<td>
<input type="button" value="select" id="id-but-select1" />
</td>
</tr>
</tbody>
</table>
References:
Array.prototype.forEach().
Array.prototype.join().* Array.prototype.push().
Array.prototype.slice().
Element.tagName.
Function.prototype.call().
String.prototype.toLowerCase().
This will do it:
<!DOCTYPE HTML>
<html>
<head>
<title>Show id values</title>
<script language="javascript">
function showValue(nodeID){
var myVar = document.getElementById(nodeID).parentNode.parentNode.childNodes;
var myTxt = "";
for(i=0; i<myVar.length; i++){
if(myVar[i].id){
if(myVar[i].id != ""){
myTxt += myVar[i].id + '\n';
}
}
}
alert(myTxt);
}
</script>
</head>
<body>
<table>
<tr>
<td id="pres0">Bear</td>
<td id="cod0">ddfd</td>
<td id="id0">23</td>
<td><input type="button" value="select" id="id-but-select0" onclick="showValue(this.id)" /></td>
</tr>
<tr>
<td id="pres1">Cat</td>
<td id="cod1">AZ</td>
<td id="id1">121</td>
<td><input type="button" value="select" id="id-but-select1" onclick="showValue(this.id);" /></td>
</tr>
</table>
<!-- the total count of the select of the database -->
<input id="nbra" type="hidden" value="2">
</body>
</html>
You can add an on-click event to your buttons and then access that td's siblings for their properties, say id, text etc.
<tr>
<td id="pres0">Bear</td>
<td id="cod0">ddfd</td>
<td id="id0">23</td>
<td><input type="button" value="select" id="id-but-select0" onclick="makeAlert(this)"></td>
</tr>
<tr>
<td id="pres1">Cat</td>
<td id="cod1">AZ</td>
<td id="id1">121</td>
<td><input type="button" value="select" id="id-but-select1" onclick="makeAlert(this)"></td>
</tr>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
function makeAlert(divObj){
var tds = $(divObj).parent().siblings();
tds.each(function( index ) {
alert($( this ).attr('id') );
});
}
</script>
<html>
<head>
</head>
</body>
<table border="1">
<tr>
<td id="pres0">Bear</td>
<td id="cod0">ddfd</td>
<td id="id0">23</td>
<td><input type="button" value="select" id="id-but-select0"></td>
</tr>
<tr>
<td id="pres1">Cat</td>
<td id="cod1">AZ</td>
<td id="id1">121</td>
<td><input type="button" value="select" id="id-but-select1"></td>
</tr>
</table>
<!-- the total count of the select of the database -->
<input id="nbra" type="hidden" value="2">
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(function(){
$('table input[type=button][value="select"]').click(function(){
$(this).closest('table').find('tr').each(function(){
alert($(this).find('td:eq(2)').html());
});
})
})
</script>

incrementing the value of a input field in the cloned row

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.

Categories