Undefined when retrieving text from element - javascript

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>

Related

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

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>

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

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"/>

How to add row in html table on top of specific row?

I have a table, and each row has a button to add a new row on top of it. Each row has new inputs.
I know how to add a row on top of the table, but not on top of each row that I'm clicking on the button. Would anyone have a tip on how to solve it? I might be able to do it, but the solution I see is very complicated, and I'm sure there must be a smarter solution.
Oh, also I don't know how to update the parameter sent in the insertNewRow(id) function.
So far this is what I have:
<script type="text/javascript">
function insertNewRow(id){
var row = document.getElementById("bottomRow");
var newrow = row.cloneNode(true);
console.log(newrow);
var newInputs = newrow.getElementsByTagName('input');
var allRows = row.parentNode.getElementsByTagName('tr');
row.parentNode.insertBefore(newrow, row);
var i=row.rowIndex;
console.log(i);
}
</script>
<table id="myTable">
<tr>
<td>Title1:</td>
<td></td>
<td>Title2:</td>
<td></td>
<td>Title3:</td>
<td></td>
<td></td>
</tr>
<tr>
<td><input class="c1" readonly maxlength="9" size="7" id="gTop" type="text" value ="11"></td>
<td> <-></td>
<td id="l1"><input class="c2" style="width:35px;" maxlength="9" size="7" type="text" id="lTop" value="33"></td>
<td>=</td>
<td id="rv1"><input id="rvTop" input class="c2" style="width:105px;" maxlength="100" size="37" type="text" value="blahblahblah"></td>
<td></td>
<td>x</td>
</tr>
<tr id="bottomRow">
<td><input class="c1" readonly maxlength="9" size="7" id="gBottom" type="text" value =""></td>
<td> </td>
<td id="l1"><input class="c2" style="width:35px;" maxlength="9" size="7" type="text" id="lBottom" value="11"></td>
<td>=</td>
<td id="rv1"><input id="rvBottom" input class="c2" style="width:105px;" maxlength="100" size="37" type="text" value="blahblahblah"></td>
<td><button type="button" onclick="insertNewRow(1)">+</button></td>
<td>x</td>
</tr>
</table>
In the onclick attribute, instead of just calling insertNewRow(), do something like
insertNewRow.apply(this);
The this keyword inside the onclick attribute is a reference of the clicked element. With insertNewRow.apply(this), we'll be calling insertNewRow() and at the same time, assign the this keyword inside that function call to the clicked element or in this case, the button (if we don't do that, this inside insertNewRow() will be a reference to the Window object instead). Then in, your insertNewRow() function, check if the current element being clicked on is a tr element. If not, go up by one level and see if that element is a tr element. Keep doing that until you get to the first tr element. So, basically you'll be searching for the closest tr element.
<button type="button" onclick="insertNewRow.apply(this);">+</button>
function insertNewRow(){
var row = null,
el = this;
// Get the closest tr element
while (row === null)
{
if (el.tagName.toLowerCase() === 'tr')
{
row = el; // row is now the closest tr element
break;
}
el = el.parentNode;
}
// Rest of the code here
}​
JsFiddle
If you're still not sure what Function.apply() is, take a look at the documentation here.

Get value from a textarea and place it in a new textarea with some added texts

I have a textarea (txtar1) that will be filled up by a user with HTML codes.
I have a 'generate' button;
When the 'generate button is clicked, the value from txtar1 will be placed in a another textarea (txtar2). But with some added css code.
here's what I've done:
HTML:
<table>
<tr>
<td valign="top"><label>Enter HTML Code : </label></td>
<td><textarea id="htmlcode_txtarea"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="button" name="" id="submit_btn" value="Generate" /></td>
</tr>
<tr id="new_html">
<td><label>New HTML</label></td>
<td><textarea id="new_htmlcode_txtarea"></textarea></td>
</tr>
javascript/jquery:
jQuery('#submit_btn').click(function(){
var newVal = jQuery('#htmlcode_txtarea').attr('value');
var addVal = "#af-form-1031686823 .af-element{float:left;}" +
"#af-form-1031686823 .af-clear{display:none}:" +
"#af-form-1031686823 .af-body input.text{width: 150px!important;margin0right:15px!important}" +
"#af-form-1031686823 .buttonContainer{margin-top:-6px!important}";
jQuery('#new_html').show();
jQuery('#new_htmlcode_txtarea').attr('value',newVal);
});
What should i Do?
easy wato achieve is make use of .val() function
$("#textarea2").val($("#textarea1").val() + "text to append ")

Categories