I can take a table's first row's td values from cefsharp chromiumwebbrowser with this code but I need all rows value. How to get each rows value? Thanks for answer.
private void GetTable ()
{
const string script = #"(function(){
let table = document.querySelector('table'); // <table class='table table-striped'>
let td = table.getElementsByTagName('td');
return [ td[0].innerText, td[1].innerText ];
})();";
browser.GetMainFrame().EvaluateScriptAsync(script).ContinueWith(x =>
{
var response = x.Result;
if (response.Success && response.Result != null)
{
// We cast values as CefSharp wouldn't know what to expect
List<object> jsResult = (List<object>)response.Result;
string s1 = (string)jsResult[0]; // td[0].innerText
string s2 = (string)jsResult[1]; // td[1].innerText
Console.WriteLine("s1: " + s1);
Console.WriteLine("s2: " + s2);
// In my example HTML page, it will output:
// s1: This is 1st
// s2: This is 2nd
}
});
}
I got this code from https://stackoverflow.com/a/55731493/3809268 Thanks this codes owner.
First, you need to change part of script.
Try this:
.
.
.
let td = table.getElementsByTagName('td');
let arr = [];
for (var i = 0; i < td.length; i++) {
arr.push(td[i].innerText);
}
return arr;
Then change C# code:
.
.
.
if (response.Success && response.Result != null)
{
List<object> jsResult = (List<object>)response.Result;
foreach (var item in jsResult)
{
Console.WriteLine("s: " + item.ToString());
}
}
In script we have created array with innerText of each td element. Then use foreach to read each element from your list.
Related
Im using REDIPS library so i can drag and drop some elements in a table. Following the provided examples by the library, I want to get the save_content() result as an array so I can insert those values inside my DB. This is my approach, but it doesn't work. Right now I get the value in an input displayed as text
save_content = function (tbl) {
var query = '', // define query parameter
tbl_start, // table loop starts from tbl_start parameter
tbl_end, // table loop ends on tbl_end parameter
tbl_rows, // number of table rows
cells, // number of cells in the current row
tbl_cell, // reference to the table cell
t, r, c, d; // variables used in for loops
// first sort tables array to it's original order
tables.sort(function (a, b) {
return a.idx - b.idx;
});
// if input parameter is undefined, then method will return content from all tables
if (tbl === undefined) {
tbl_start = 0;
tbl_end = tables.length - 1;
}
// if input parameter is out of range then method will return content from first table
else if (tbl < 0 || tbl > tables.length - 1) {
tbl_start = tbl_end = 0;
}
// else return content from specified table
else {
tbl_start = tbl_end = tbl;
}
// iterate through tables
for (t = tbl_start; t <= tbl_end; t++) {
// define number of table rows
tbl_rows = tables[t].rows.length;
// iterate through each table row
for (r = 0; r < tbl_rows; r++) {
// set the number of cells in the current row
cells = tables[t].rows[r].cells.length;
// iterate through each table cell
for (c = 0; c < cells; c++) {
// set reference to the table cell
tbl_cell = tables[t].rows[r].cells[c];
// if cells isn't empty (no matter is it allowed or denied table cell)
if (tbl_cell.childNodes.length > 0) {
// cell can contain many DIV elements
for (d = 0; d < tbl_cell.childNodes.length; d++) {
// childNodes should be DIVs, not \n childs
if (tbl_cell.childNodes[d].tagName === 'DIV') { // and yes, it should be uppercase
var value = $(tbl_cell).find("input").val();
query += 'p[]=' + tbl_cell.childNodes[d].id //obj id
+ '_' + value + '_' + r + '_' + c + '&';
}
}
}
}
}
}
// cut last '&'
query = query.substring(0, query.length - 1);
// return prepared parameters (if tables are empty, returned value could be empty too)
return query;
};
I would like to get the query value as an array so i can insert the values into the database without using $_REQUEST
function save() {
$('#moverCita').modal('toggle');
var content = REDIPS.drag.save_content();
document.getElementById("moverCitaRow").value = content;
}
I get the value as text inside the input
update.php
if (isset($_POST['submit'])){
if(isset($_POST['moverCitaRow'])){
if (!empty($_POST['moverCitaRow'])) {
$content = $_POST['moverCitaRow'];
$content = #$_REQUEST['p'];
if(is_array($content)) {
foreach ($content as $c) {
list($job_id, $job_bay_id, $row, $col) = explode('_', $c);
try {
update_calendar($job_id, $job_bay_id, $row, $col);
} catch (Exception $ex) {
$_SESSION["errorMsg"] = $ex->getMessage();
$_SESSION["errorType"] = "danger";
}
}
}
}
else {
echo '<center><strong style="color:red;">Llenar todos los campos
requeridos</strong></center><br>';
}
}
}
So I have this code where I'm trying to print(physical print as in paper) a table when a button is clicked, which is populated with array data.
I managed to print the array data but I can not seem to find on how to put this in a table.
also is there a better way than document.write()I am not a huge fan of it ?
var Obj = [];
function printDiv(){
var divContents = document.getElementsByClassName("test")
console.log(divContents)
//if($("div").hasClass("test") == true){// can use jquery hasfind in order to check if acive class exists if yes get content of child divs
//expand if this option is better
//console.log('istrue');
//}
for(var i = 0; i< divContents.length; i++){
Obj.push(divContents[i].textContent +'</br>')
}
var a = window.open('','','height=500,width=500');
a.document.write('<html>');
a.document.write('<body><h1>Div contents are<h1><br>');
a.document.write('<table><tbody><tr>')
a.document.write('<td>'+ Obj.join(' ')+'<td>');
a.document.write('</tr></tbody></table></body></html>');
a.document.close();
a.print();
Obj = [];
}
expected outcome would be:
work order and date are not yet populated this is just a test file to use in a bigger project.
jsfiddle : https://jsfiddle.net/yLz7stxr/
thanks in advance.
here is the solution you just need to replace ${} in code link.
code: https://jsfiddle.net/vnxd1pew/3/
I assume we got an array of objects here.
const dataObject = {'name': null, 'age': null, 'favoriteFood': null};
let data = [];
let row = {...dataObject};
row.name = 'John';
row.age = '10';
row.favoriteFood = 'Pancakes';
data.push(row);
row = {...dataObject};
row.name = 'Jenny';
row.age = '11';
row.favoriteFood = 'Pie';
data.push(row);
row = {...dataObject};
row.name = 'James';
row.age = '12';
row.favoriteFood = 'Fries';
data.push(row);
// build table header
let tableHeaderColumns = Object.keys(data[0]).map(colKey => `<th>${colKey}</th>`).join('');
const tableHeader = `<tr align=left>${tableHeaderColumns}</tr>`;
// build table rows
let i = 0;
let tableRows = '';
let greyStyle = 'background-color: #EEE;';
data.forEach(function(rowObject) {
const row = Object.values(rowObject).map(colValue => `<td>${colValue}</td>`).join('');
let rowStyle = '';
if(++i%2) {
rowStyle = greyStyle;
}
tableRows += `<tr style='${rowStyle}'>${row}</tr>`;
});
// build table (add desired styling)
const table = `<table cellspacing=0 width=500 border=1 borderColor=#EEE style='border-collapse: collapse;'>${tableHeader}${tableRows}</table>`;
// for demonstration display in div
document.querySelector('div').innerHTML = table;
<div />
I created 3 objects that nest arrays of one another - we'll call them Table, Row and Column so I can show you what's wrong. Table has an array of Rows, and Row has an array of Columns. When I call properties of the Rows from Table, no problem. When I call properties of the Columns from Row, it says undefined, but in the debugger and the console it recognizes the object and it's properties. Maybe I've been staring at it too long but I can't see a fundamental difference.
I stripped the Table layer to be sure it wasn't an issue with nested objects. Here's the code, not working:
function Column()
{
this.sampleProp = "testprop";
this.content = "<td>sometext</td>";
}
function Row(columns)
{
this.columns = [];
this.columns = columns;
this.outputRows = function()
{
var temp = "<tr>";
for(var i = 0; i < this.columns.length; i++)
{
//this is the line that doesn't work and comes out as undefined:
temp += this.columns[i].content;
console.log("Problem: " + this.columns[i].content);
//yet the object exists, and has the correct properties:
console.log(this.columns[i]);
}
temp += "</tr>";
return temp;
};
}
function test()
{
var col = new Column();
console.log("Printing out the value from here works fine: " + col.content);
var cols = [col];
console.log("It's also fine when it's called from an array: " + cols[0].content);
var row = new Row([cols]);
console.log(row.outputRows());
}
Here is the interaction between the parent layer and the rows, working fine:
function Table(rows)
{
this.rows = [];
this.rows = rows;
this.outputTable = function()
{
var temp = "<table>";
for(var i = 0; i < this.rows.length; i++)
{
temp += this.rows[i].outputRows();
}
temp += "</table>";
return temp;
};
}
and the updated test function:
function test()
{
var column = new Column();
var cols = [column];
var row = new Row([cols]);
console.log(row.outputRows());
var rs = [row, row];
var table = new Table(rs);
console.log(table.outputTable());
}
Two rows print out as expected this way, with undefined inside each. I originally had column.content written as a function, it doesn't make a difference.
Please tell me what stupid mistake I'm missing here!
Change that line :
var row = new Row([cols])
into
var row = new Row(cols)
since cols is already an array, you don't need to put it in an array again.
function Column() {
this.sampleProp = "testprop";
this.content = "<td>sometext</td>";
}
function Row(columns) {
// removed this.columns = [] since you are assigning it in the next line
this.columns = columns;
this.outputRows = function() {
var temp = "<tr>";
for (var i = 0; i < this.columns.length; i++) {
//this is the line that doesn't work and comes out as undefined:
temp += this.columns[i].content;
}
temp += "</tr>";
return temp;
};
}
function test() {
var col = new Column()
console.log("Printing out the value from here works fine: " + col.content);
var cols = [col];
console.log("It's also fine when it's called from an array: " + cols[0].content);
var row = new Row(cols); // the problem was here
console.log(row.outputRows());
}
test()
I'm trying to grab the cell values from an HTML table generated from another PHP code. That I can use the result to send a rendezvous at final user.
My current JSFiddle can grab some values but not like I want. I need to retrieve the attrib title & value from the button in the TD, my problem is currently the code return data from morning day and jump to the next morning day.
How I can return entire day value & title data's for each available days in the table ?
Code :
$(document).ready(function(){
eachCell();
function eachCell(){
var cellInnerText = [];
var cellValue = [];
var out = document.getElementById("out");
var out2 = document.getElementById("out2");
$('#ft_agenda tbody tr').each(function(index) {
// console.log("index ", index, " this: " , this, "this.attr(rel)", $(this).attr('rel'), "$(this).text()", $(this).text());
console.log($(":first-child", $(this))[0]);
cellInnerText.push($("td button", $(this)).attr('value'));
cellValue.push($("td button", $(this)).attr('title'));
});
out.innerHTML = cellInnerText.join(" | ");
out2.innerHTML = cellValue.join(" | ");
}
});
// Try this code on your jsfiddle
// https://jsfiddle.net/g60ogt8c/1/
$(function() {
function findColumnByDate(date) {
var col;
$('#ft_agenda thead th').each(function(idx) {
if ($(this).text().trim() == date.trim()) col = idx;
});
return col;
}
function showAvailableTimes(date) {
var times = [],
column = findColumnByDate(date);
if (column) {
var $rows = $('#ft_agenda tbody td:nth-of-type('+column+')');
if ($rows.length) {
times[0] = '';
$rows.find('button').each(function() {
times[times.length] = $(this).attr('value')+' - '+$(this).attr('title');
});
times[0] = 'For date '+date+' found '+(times.length-1)+' free terms';
} else {
times[0] = ['No free terms for date: '+date];
}
} else {
times[0] = ['Invalid date '+date+' or date not found'];
}
return times;
}
// Function showAvailableTimes() now returns array.
// In index 0 is status message and if available times found,
// these lies on indexes 1 and more.
// Use it this way:
$('#out').html('');
showAvailableTimes('15-09-2016').forEach(function(item) {
$('#out').append(item + '<br>');
});
// Or this way:
// Jsonify returned array and send it toSome.php.
var json = JSON.stringify(showAvailableTimes('09-09-2016'));
$.post('toSome.php', {times: json});
// Or if there are free terms, filter status message
// and send just free terms - without status message.
var times = showAvailableTimes('09-09-2016');
if (times.length > 1) {
var json = JSON.stringify(times.filter(function(itm,idx){return idx>0}));
$.post('toSome.php', {times: json});
// Here you can see that status message was skipped
$('#out2').text(json);
}
});
I have a function that scans the child elements of a td element in a table for the string "green.png" in the columns declared in the "columns" array. It then passes the result to a function which reorders the table based on the result.
I am using the .every method to ensure that all the child elements in the selected columns contain "green.png" before executing, however it executes when any of the columns contain this value.
My understanding of the .every method is that it will ensures the condition is met for every object in the array before executing, but this is not occurring. Could someone advise what is missing/incorrect with my code?
Here is the code that parses the element:
function checkRowGreen(tenant) {
var columns = ["COLUMN1", "COLUMN2", "COLUMN3", "COLUMN4", "COLUMN5"];
var count = 0;
columns.every(function(column) {
var element = document.getElementById(tenant + column);
if(element != null && element.firstElementChild != null && element.firstElementChild.src.indexOf('green.png') > -1) {
console.log("[INFO] Found successful PNG on " + tenant + " column " + column + " - found " + count);
count++;
}
});
return count > 0;
}
And here is the code that reorders the table:
if(checkRowGreen(tenant)) {
var row = document.getElementById(tenant + "Row");
var table = document.getElementById("tenantTable");
if(row == null || table == null) return true;
var cells = row.getElementsByTagName("td");
table.deleteRow(row.rowIndex);
var newRow = table.insertRow(-1);
newRow.id = rowID;
for(var i = cells.length-1; i >= 0; i--) {
bugout.log("[INFO] inserting cell.." + i + " out of " + cells.length);
var newCell = newRow.insertCell(0);
newCell.innerHTML = cells[i].innerHTML;
newCell.id = cells[i].id;
}
}
Syntax should be something like:
if(myArray.every(myFuncName))
{
...
}
or
var result = myArray.every(myFuncName);
or
var result = mArray.every(element => element.age >= 5);
etc.