This seems very simple but I just can't get my head around it. I am trying to insert data I get back and replace the cell contents at the specified cell index. I am getting the data (Kevin) and index (0) back from the function call's input parameters. But I'm just not able to insert this data into the desired cell. I have tried insertCell function, but this won't replace the contents, it'll just keep appending new cells.
My console.logs report the correct index and data, I've tried inserting/replacing the content of the cell like this: td[index].innerHTML = data but this gives an error, apparently td[index] returns a object HTMLTableCellElement, so i can't do it this way.
HTML:
<table>
...
<tbody>
<tr id="data-row-body">
<td></td> //need to insert here
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Javscript:
function exeAPI(api, key, index, callback) {
$.ajax({
url:"../lib/getData.php",
type: "POST",
data: {
name: name,
api: api
},
dataType: "text",
success:function(result){
console.log(result);
if(result){
try {
var jsonText = result.substr(result.indexOf('{'));
console.log("this is the jsontext: " + jsonText);
var jsonObj = JSON.parse(jsonText);
callback(jsonObj.response.result[key], index);
} catch(e) {
console.log(e);
alert("Error getting rack data!");
}
}
}
});
//getting back "Kevin" and "0" as parameters to insert here
function exeAPIcallback(data, index){
var td = $('#data-table tbody td');
var tr = $('#data-table tbody tr');
var row = document.getElementById("data-row-body");
console.log("This is the cell index: " + th[index].innerHTML + " ,index: " + th[index]);
console.log("This is the cell index: " + td[index]);
td[index].innerHTML = data; // this doesn't work
}
function popupParamChecker(){
exeAPI("getData.php", "Kevin", 0, exeAPIcallback);
$("#dialog-params").dialog({
resizable: false,
width: 1000,
modal: true,
draggable: false,
buttons: {
Confirm: function() {
$( this ).dialog( "close" );
}
}
});
}
Is there an easier way of doing this?
The count of row may be many, so I added one param for your APICallback.
Below is the codes:
1. First select our all rows under the table by $('table tbody tr')
2. use .eq(index) to get the specific row
3. .find() all tds then get the specific cell to change the text.
function exeAPIcallback1(data, row, col){
let td = $('table tbody tr').eq(row).find('td').eq(col);
td.text(td.text()+data)
}
function exeAPIcallback2(data, row, col){
$('table tbody tr').eq(row).find('td').eq(col).text(data);
}
table td{
width:10px;
height:10px;
border:1px;
background-color:yellow;
}
table td:nth-child(even){
background-color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="exeAPIcallback1('test',0,0)"> Test Insert</button>
<button onclick="exeAPIcallback2('test',0,0)"> Test Replace</button>
<table>
<tbody>
<tr id="data-row-body">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Use the following function to add content to a table cell.
function add_content_to_cell(table_selector, row_number, cell_number, content) {
$(table_selector).find('tr')
.eq(row_number-1).find('td').eq(cell_number-1)
.append(content);
}
Simply choose the table id, the row number, the cell number and the content you wish to add.
Usage:
add_content_to_cell('#my_table', 2, 5, "I am some content")
Result:
With jQuery:
$('#data-row-body').find('td').eq(index).text(data); /* strips down html, if any */
OR
$('#data-row-body').find('td').eq(index).html(data); /* with html tags */
See if this works, with your current snippet
change
var td = $('#data-table tbody td');
to
var td = $('#data-row-body').children('td');
$(td[index]).html(data);
here, assuming that index is always within the bounds of
Related
I want value of first td onclick whenever i click on any of the table row. I am using jquery below code to create table rows dynamic.
This data is javascript array of key value pairs.
$(document).ready(function(){
$.each(Data, function(key, value) {
$('#idforappend').append('<tr class="tr_use"><td>'+key+'</td><td>'+key+'</td><td>'+value+'</td></tr>');
});
});
Now when i click on any row i want first td value only that row. How can we do that please help.
I have created a dynamic table using jS. when clicking on the row it will console 1st TD value only.
jQuery('document').ready(function(){
function createTable(tableData) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.body.appendChild(table);
}
createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"]]);
jQuery('tr').on('click', function(){
console.log(jQuery(this).find('td').first().text());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This is the solution thanks.
$(document).ready(function(){
// code to read selected table row cell data (values).
$(".btnSelect").on('click',function(){
var currentRow=$(this).closest("tr");
var col1=currentRow.find("td:eq(0)").html();
});
});
Just add the same onClick handler on each row when you are creating your table.
$(document).ready(function(){
$.each(Data, function(key, value) {
$('#idforappend').append('<tr class="tr_use" onClick="handle(event)"><td>'+key+'</td><td>'+key+'</td><td>'+value+'</td></tr>');
});
});
Your resultant table should be something similar to the below table
<table>
<tr onClick="handle(event)">
<td>key1</td>
<td>value1</td>
</tr>
<tr onClick="handle(event)">
<td>key2</td>
<td>value2</td>
</tr>
</table>
Your event handler
function handle(event){
console.log(event.currentTarget.children[0].textContent);
}
I have a table element defined below as $table. I am trying to run a function on every cell a specific column that is defined by a specific table heading - qc_statusTh. I have found the index of that table heading (qc_statusColumnIndex) and have been able to grab the next table cell in that column - qc_statusCell.
However, I am not able to loop through the table cells and run a function on each table cell in that column.
Here is the JavaScript code I have so far:
$(document).ready(function() {
var $table = $("table.tables.list");
if ($table.length > 0) {
var qc_statusTh = $("th.headersub:contains('qc_status')");
var qc_statusColumnIndex = $(qc_statusTh).index();
var qc_statusCell = $($table).find("td").eq(qc_statusColumnIndex);
// this does not work. this only replaces the first cell
// in the row after qc_statusTh with "TESTING"
$(qc_statusCell).each(function() {
$(this).replaceWith("TESTING");
});
}
});
How can I edit this code to loop through each cell in the table that has an equal index to qc_statusColumnIndex?
If you think about it, you really want to iterate (using each) over the rows of the table, not the cells. If you do that, you can then grab the nth td element from each row and apply your transformation.
$(document).ready(function() {
var $table = $("table.tables.list");
if ($table.length > 0) {
var qc_statusTh = $("th.headersub:contains('qc_status')");
var qc_statusColumnIndex = $(qc_statusTh).index();
var qc_rows = $($table).find('tr');
$(qc_rows).each(function() {
$(this).find('td').eq(qc_statusColumnIndex).replaceWith("TESTING");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tables list">
<thead>
<th class="headersub">qc_example</th>
<th class="headersub">qc_status</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Ok</td>
</tr>
<tr>
<td>2</td>
<td>Ok</td>
</tr>
<tr>
<td>3</td>
<td>Error</td>
</tr>
</tbody>
</table>
I'm trying to run through a table and change each cell based on the row. Table example:
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
Function example (in script under body):
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
$(document).load(myFunction);
The example shown is non-specific version of the actual function I'm trying to run.
To be clear, I have linked to the jQuery 2.1 CDN, so the page should be able to read jQuery.
Console shows no errors, but still does not run appear to run the function. Checking the tested row in the console shows no change to the html in the div. Any advice for this?
When I run it I get an error on r.find() because .find() is a jQuery function and needs to be called on a jQuery object, which r is not. Simply wrapping it in a $() works.
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
https://jsfiddle.net/k50o8eha/1/
You may need to do asomething similar to the c.getChild();
Here's a simplified version :
$("#myTable tr").each(function(i, r){
if(i==1)
{
$(this).find('td').each(function()
{
$(this).find("div").html("html here");
});
}
});
Example : https://jsfiddle.net/DinoMyte/4dyph8jh/11/
Can you give this a try...
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
});
or shorthand...
$(function() {
});
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = $(c).children('div');
square.text('html here');
});
}
});
});
table{
background-color: #eee;
width: 300px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
This works, you can try this
JSBIN
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i){
if(i==1){//to edit second row, for example
$(this).find('td').each(function(j){
$(this).find('div').html('html here');
});
}
});
}
$(document).ready(myFunction);
first the "id" should be unique to an element... but ok, this should do the trick:
$(document).ready(function(){
$("#myTable>tr:odd").children("div").text('html here');
});
If you want to put html code in the div, change text for html. if you want to specify the row then:
$(document).ready(function(){
myRow = //set its value...
$("#myTable>tr").each(function(idx, element){
if(idx == myRow){
element.children("div").text('html here');
}
}, myRow);
});
Hello all NightWatch adopters,
I am trying to parse a table with the following format to get a a list of rows and the cell in each rows
<tbody>
<tr> // 1 row
<td>Item A</td> // name
<td>John</td> // owner
<td>Monday</td> // create date
</tr>
<tr> // 2 row
<td>Item B</td>
<td>Mary</td>
<td>Tuesday</td>
</tr>
</tbody>
The code now looks like this which calls the function below.
browser.elements('css selector', 'tbody tr', getResultsList);
Where my function for parsing now looks like this.
function getResultsList(rowResults){
// Here we get the correct set of rows
console.log(rowResults.length + ' rows found'); // this returns 2
// Main loop going through the rows
for(var i = 0; i < rowResults.value.length; i++) {
var row = rowResults.value[i];
console.log(row.value + ' -- row item');
// need to get the <td> inside row
}
}
In Java webdriver we can just do the following
List<WebElements> rows = driver.getElements("tbody tr");
for (WebElement row : rows) {
row.getElement(' > td:nth-child(1)') // name
row.getElement(' > td:nth-child(2)') // creator
row.getElement(' > td:nth-child(3)') // date
}
I wanted to know if there is any straight forward way to do this in NightWatchJS similar how we do this in Java via child WebElement where we can just call startingWebElement.getElement(childlocator); without having to start all the way from the top and dynamically build/chain the locators e.g.
// name
browser.getText('css selector', 'tbody tr:nth-child('+i+') td:nth-child(1)')
// creator
browser.getText('css selector', 'tbody tr:nth-child('+i+') td:nth-child(2)')
// date
browser.getText('css selector', 'tbody tr:nth-child('+i+') td:nth-child(4)')
Any comments, suggestions, concerns, tips is greatly appreciated.
See if this works for you:
Page.getTableRows((rows) => {
rows.forEach((row) => {
client.elementIdElements(row.ELEMENT, 'tag name', 'td', (result) => {
console.log(`row td length ${result.value.length}`);
result.value.forEach((cell) => {
client.elementIdText(cell.ELEMENT, (text) => {
console.log(`cell text ${text.value}`);
})
});
});
});
});`
Implementation of getTableRows
getTableRows(callback) {
this.api.elements('css selector', \`${this.elements.table.selector} tbody tr\`, (data) => {
if(data.state === 'success'){
callback.call(this, data.value);
}
});
},
I would like the following script to move a table row to the top of a table. I can't figure out how to reference the id of the first row, however, since the ID is set dynamically, I tried row.insertAfter(row.first()); but it's making the row disappear instead of moving it. Any ideas how to reference the top row?
$(".top").click(function(){
var row = $(this).parents("tr:first");
if ($(this).is(".top")) {
row.inserAfter(row.first());
} else {
return false;
}
});
<tbody id="sortable">
<tr id="row1">
<td>Top</td>
</tr>
<tr id="row2">
<td>Top</td>
</tr>
<tr id="row3">
<td>Top</td>
</tr>
</tbody>
This works...
$(".top").click(function() {
var thisRow = $(this).parent().parent();
var firstRow = thisRow.parent().find("tr:first").not(thisRow);
thisRow.insertBefore(firstRow);
});
$(".top").click(function(){
var tr=this.parentNode.parentNode;
tr.parentNode.insertBefore(tr.parentNode.firstChild,tr);
tr.parentNode.removeChild(tr);
}
Do you wanna do something like this?
$(".top").click(function(){
var $this = $(this); // make a reference to the current element
$.ajax({
url: 'your/ajax/url.php',
success: function(data) {
// do what you want with data,
// and then move the row on top
// of the table, like so
var row = $this.parents("tr");
var first_row = row.parent().find('tr:first');
if (row && first_row && row != first_row) {
row.insertBefore(first_row);
}
}
});
return false; // stay on the page
});
Check http://api.jquery.com/jQuery.ajax/ for more info
var row = $(this).find("tr").eq(0);