select dynamically muiltiple element from a html table - javascript

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>

Related

How to get all values inside HTML table using JQuery

I have a table which looks like below and i want to get all values inside the table including the value of text box and check box.
<div class="container-fluid">
<h1 class="h3 mb-4 text-gray-800"><?= $title; ?></h1>
<div class="container" style="text-align: left">
<table class="table table-sm" id="tbl">
<thead>
<tr>
<th>No</th>
<th>Checklist Item</th>
<th>Cheklist</th>
<th>Actual</th>
<th>Recomended</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row">1</td>
<td>Check and clean rubber roller cage</td>
<td><input type="checkbox" name="chek" id="check"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td scope="row">2</td>
<td>Tension Rod all </td>
<td><input type="checkbox" name="chek" id="check"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td scope="row">3</td>
<td>Delete all unnecessary file from system</td>
<td><input type="checkbox" name="chek" id="check"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</table>
save
</div>
when i grab all value using this script i cant get value inside the text box and checkbox
$(document).on('click', '#save', function() {
var myRows = [];
var headersText = [];
var $headers = $("th");
// Loop through grabbing everything
var $rows = $("tbody tr").each(function(index) {
$cells = $(this).find("td");
myRows[index] = {};
$cells.each(function(cellIndex) {
// Set the header text
if (headersText[cellIndex] === undefined) {
headersText[cellIndex] = $($headers[cellIndex]).text();
}
// Update the row object with the header/cell combo
myRows[index][headersText[cellIndex]] = $(this).text();
});
});
var myObj = {
"Array": myRows
};
alert(JSON.stringify(myObj));
});
I want to convert it to JSON but the value of text box and check box not shows inside table. Kindly help me to resolve this issue.
Thank you in advance.
You can find the input and use .val() to get its value if the table cell's text is empty. Checkboxes and text inputs will need to be handled separately.
const text = $(this).text();
if(text){
myRows[index][headersText[cellIndex]] = text;
} else {
const input = $(this).find('input');
if(input.is(":checkbox")){
myRows[index][headersText[cellIndex]] = +input.prop('checked');
} else {
myRows[index][headersText[cellIndex]] = input.val();
}
}

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

CasperJS to select a checkbox with specified text

I want to use casperJS to automatically select a checkbox
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="1" data-crdid="0005442" data-numcrd="3" value="">
</td>
<td>Data Structures and Algorithms</td>
<td>INT2203></td>
</tr>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="2" data-crdid="0005682" data-numcrd="3" value="">
</td>
<td>Machine Learning</td>
<td>INT2204></td>
</tr>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="3" data-crdid="003643" data-numcrd="3" value="">
</td>
<td>Artificial Intelligence</td>
<td>INT2205></td>
</tr>
The first column is the checkbox to select.
The second one is the name of the subject and the last one is the ID of the subject.
Now I just know the ID of the subject: INT2204 and I want to use casperjs to select the box of this subject. However, the only thing to distinguish is data-crdid which I have no clue.
Are there anyway to select the checkbox of the subject with ID 'INT2204' by casperjs?
You can use jQuery to filter on the element and get the siblings. This can be evaluated inside the page by CasperJS if you inject jQuery (if it isn't already).
Inject jQuery:
casper = require('casper').create();
casper.start();
casper.open('some url');
casper.then(function doSomething() {
this.page.injectJs('relative/local/path/to/jquery.js');
this.evaluate(function (courseId) {
$('td').filter(function() {
return $(this).text() === courseId;
}).siblings().find('input').prop('checked', true);
}, 'INT2203>');
});
Example in Browser:
var courseId = 'INT2203>';
$('td').filter(function() {
return $(this).text() === courseId;
}).siblings().find('input').prop('checked', true);
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Checkbox test</title>
</head>
<body>
<table>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="1" data-crdid="0005442" data-numcrd="3" value="">
</td>
<td>Data Structures and Algorithms</td>
<td>INT2203></td>
</tr>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="2" data-crdid="0005682" data-numcrd="3" value="">
</td>
<td>Machine Learning</td>
<td>INT2204></td>
</tr>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="3" data-crdid="003643" data-numcrd="3" value="">
</td>
<td>Artificial Intelligence</td>
<td>INT2205></td>
</tr>
</table>
</body>
</html>
I finally found a way to solve my problem without using jQuery.
Here is the HTML code which I copied from #Evers answer:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Checkbox test</title>
</head>
<body>
<table>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="1" data-crdid="0005442" data-numcrd="3" value="">
</td>
<td>Data Structures and Algorithms</td>
<td>INT2203</td>
</tr>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="2" data-crdid="0005682" data-numcrd="3" value="">
</td>
<td>Machine Learning</td>
<td>INT2204</td>
</tr>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="3" data-crdid="003643" data-numcrd="3" value="">
</td>
<td>Artificial Intelligence</td>
<td>INT2205</td>
</tr>
</table>
</body>
</html>
I will use method getElementsInfo and getElementsAttribute of CasperJS:
First, I need to collect all the data which related to the subjects. Since the only things I know is the ID and the name of the subjects, I need to know their data-crdid in order to select the checkbox.
casper.then(function () {
// Select all the subject IDs in the table
id = this.getElementsInfo('table tr td:nth-child(3)')
.map(function (value, index, array) {
return array[index].text();
});
// Select all the data-crdid in the table
data = this.getElementsInfo('table tr td input', 'data-crdid');
});
After that, everything is simple. I just need to pick my subject by its ID and the data-crdid will have the same index in array data.
casper.then(function () {
selected = data[id.indexOf(subject)];
});
casper.thenEvaluate(function (selected) {
document.querySelector('input[data-crdid="' + selected + '"]').click();
}, selected);
Here is the full code:
var casper = require('casper').create();
var subject = 'INT2204';
casper.start();
casper.thenOpen('/{{ URL }}');
casper.then(function () {
// Select all the subject IDs in the table
var id = this.getElementsInfo('table tr td:nth-child(3)')
.map(function (value, index, array) {
return array[index].text();
});
// Select all the data-crdid in the table
var data = this.getElementsInfo('table tr td input', 'data-crdid');
var selected = data[id.indexOf(subject)];
this.thenEvaluate(function (selected) {
document.querySelector('input[data-crdid="' + selected + '"]').click();
}, selected);
});
casper.run();

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>

if input field has a value found in array, do this (jQuery/Javascript)

I've got a page with a handful of input fields.
I need to find the fields with an array of values, and if so, .remove() the closest('tr')
The markup is similar to this
<table>
<tr>
<td>
<input type="text" value="this">
</td>
</tr>
<tr>
<td>
<input type="text" value="that">
</td>
</tr>
<tr>
<td>
<input type="text" value="them">
</td>
</tr>
</table>
I need to find "this" and "that", and if they are there, remove their <tr> container (and themselves) so I'd end up with:
<table>
<tr>
<td>
<input type="text" value="them">
</td>
</tr>
</table>
I've tried this:
jQuery(document).ready(function($){
var badfields = ['this', 'that'];
var fieldvalue = $('input[type="text"]').val();
if($.inArray(fieldvalue, badfields) > -1){
$(this).closest('tr').remove();
}
});
but it doesn't seem to want to work?
You need to iterate over all the fields using .each, so something like this:
$('input[type="text"]').each(function() {
var fieldvalue = $(this).val();
if ($.inArray(fieldvalue, badfields) > -1) {
$(this).closest('tr').remove();
}
});
Example: jsfiddle
You can be very concise sometimes with jQuery. jQuery has content selectors you can use for this type of purpose:
$("input[type=text][value=this], [value=that]").parents("tr").remove();
since you don't necessarily know this or that beforehand, you can do something like this:
var badfields = ['this', 'that'];
$(badfields).each(function(i) {
$("input[type=text][value=" + this + "]").parents("tr").remove();
});
You can use each to iterate through the selector. this in your inArray scope is not the element you were looking for.
DEMO: http://jsfiddle.net/
html:
<table>
<tr>
<td>
<input type="text" value="this">
</td>
</tr>
<tr>
<td>
<input type="text" value="that">
</td>
</tr>
<tr>
<td>
<input type="text" value="them">
</td>
</tr>
</table>
js:
jQuery(document).ready(function($){
var badfields = ['this', 'that'];
$('input[type="text"]').each(function(){
if( $.inArray(this.value, badfields) > -1 ){
$(this).closest('tr').remove();
}
});
});

Categories