REDIPS get results as array from function and pass it to ajax - javascript

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>';
}
}
}

Related

Diaplaying unique element into the html table through JQuery

I need to display unique elements of already binded data in that html table by using JQuery or JavaScript. Displaying unique value means that mearging the cells having same value in the rows. The table data is dynamic but the structure is fix.
So, here is given table:
Here, I need to merge the Red colored cells as shown below.
And the required table is:
So, I need to achieve this cell merging through Jquery or javascript. As this table is created with HTML table and the data is already binded in it. By using this binded data I need to achieve the reqiured table. I need to merge more columns like this.
I have tried some coding but it is not working correctly. The code is:
jQuery('tr.tblRow').each(function(i, obj)
{
current_name = jQuery(obj).text();
var current_name_arr = current_name.split(/\t|\n| /);
/* check for repeated names */
if (current_name_arr[22] == last_selected_compNo)
{
jQuery("td.headingSpas:contains('" + current_name_arr[22] + "')").each(function(index, object)
{
if (index == 0)
{
/* check if already has rowspan attribtue */
row_span = jQuery(object).attr('rowspan') ? jQuery(object).attr('rowspan') : 1;
/* add one */
row_span++;
/* include the new rowspan number */
jQuery(object).prop('rowspan', row_span);
}
else if(index < 2)
{
/* delete the other first name cells */
jQuery(object).remove();
}
});
}
}
Please help me.
I have written my own solution for this problem. It work for me..
/*Merging rows Start (updated by Suraj)*/
/*Some changes are made in HTML table's body like adding 'id' property in each column of the table.*/
var row = 0;
var col = 0;
jQuery('tr.tblRow').each(function(n, obj) {
/*Getting the first row as text*/
current_name = jQuery(obj).text();
/*Splitting the above text value into an array using 'Regex' by '/t' and '/n'*/
var current_name_arr = current_name.split(/\t|\n/);
/*Now storing the element into an array for getting the values easily.*/
var current_name_arr1 = [];
var j = 0;
for(var i = 0; i < current_name_arr.length; i++) {
if(current_name_arr[i] == ""){}
else {
current_name_arr1[j] = current_name_arr[i];
j++;
}
}
/*Setting column*/
if(n == 0) {
col = current_name_arr1.length;
}
});
jQuery('tr.tblRow').each(function(n, obj) {
var ele = ""
var removingEle = "";
/*Merging the cells by spaning the cells and removing the duplicate cells*/
for(var l = 0; l < col - 1; l++) {
if(l == 4 || l == 5) {
continue;
}
/*Getting the element by id*/
ele = $("#pdtDetail" + row + l);
/*Getting the removing element by id*/
removingEle = $("#pdtDetail" + (row + 1) + l);
if(ele.text() == removingEle.text()) {
/* check if already has rowspan attribtue */
row_span = ele.attr('rowspan') ? ele.attr('rowspan') : 1;
/* add one */
row_span++;
/* include the new rowspan number */
ele.prop('rowspan', row_span);
/* delete the other first name cells */
removingEle.remove();
}
}
/*If element get matched then increasing row by two because we have to leave the just after commming row.*/
if(ele.text() == removingEle.text()) {
row = row + 2;
}
else {
row++;
}
});
/*Merging rows End*/
The Final Table looks like as:

c# How to get all row value from cefsharp chromium browser?

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.

.every method not matching all elements to IF statement

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.

Sorting tables in Javascript

I have the following code to sort a table using Javascript. What I want to do is make the last row of the table for totals and therefore need to append my code to remove the last row from sorting. I am having troubles with this task.
var TableSort = function ( tableId ) {
var that = this;
// Store a reference to the table node as a property
this.table = document.getElementById(tableId);
// Validate the table node
if ( this.table && this.table.nodeType != 1 ) {
throw new Error("TableSort: Table id is not a DOM element.");
}
if ( this.table.tagName != "TABLE" ) {
throw new Error("TableSort: Table id is not a table element.");
}
// Set three global properties
this.sortColumn = "";
this.sortUp = true;
this.imageNodes = [];
// Get the header nodes
var headers = this.table.getElementsByTagName("th");
// Loop through the header nodes
var header, columnName, imageNode, imageClick;
for ( var i = 0; i < headers.length; i++) {
header = headers[i];
// Create a node for the image
imageNode = document.createElement("img");
// Add the "sort arrow" images to the header column
// And set the first column as the default sort column
columnName = header.className;
if ( i == 0 ) {
this.sortColumn = columnName;
imageNode.src = "arrows_up.png";
} else {
imageNode.src = "arrows_off.png";
}
// Get the event handler for the image
imageClick = this.imageClickHandler(columnName);
// Add the event handler to the image
jsLib.event.add(imageNode, "click", imageClick);
// Add the image node to column header and to array of image nodes
header.appendChild(imageNode);
this.imageNodes[columnName] = imageNode;
}
// Sort the table
this.sort();
}
TableSort.prototype.imageClickHandler = function (columnName) {
var that = this;
// return an event handler
return function () {
// If current sort column, toggle the sort direction
if ( that.sortColumn == columnName ) {
that.sortUp = ! that.sortUp;
// Otherwise...
} else {
// Set the image for the old sort column
that.imageNodes[that.sortColumn].src = "arrows_off.png";
// Switch the current sort column and sort ascending
that.sortColumn = columnName;
that.sortUp = true;
}
// Set the appropriate arrows for the current sort column
if ( that.sortUp ) {
that.imageNodes[that.sortColumn].src = "arrows_up.png";
} else {
that.imageNodes[that.sortColumn].src = "arrows_down.png";
}
that.sort();
}
}
TableSort.prototype.sort = function () {
var that = this;
if ( this.sortColumn == "" ) return;
// Get the rows from the table
var rowNodes = this.table.getElementsByTagName("tr");
if (rowNodes.length <= 1 ) return;
// Store a reference to each row in the rows array
var rows = [];
for ( var i = 0; i < rowNodes.length; i++) {
rows.push( rowNodes[i] );
}
// Get a reference to the tbody node
var tbodyNode = rows[0].parentNode;
// Remove the header row from the array (but not the DOM)
rows.shift();
// Remove all rows except the header row from the DOM
var row;
for ( i = 0; i < (rows.length); i++ ) {
row = rows[i];
row.parentNode.removeChild(row);
}
// Define two functions that check for data types
var isMoney = function ( value ) {
var m = value.replace( /[$,]/g, "" );
return ! isNaN(m);
}
var isDate = function ( value ) {
var d = new Date(value);
return ! isNaN(d);
}
// Define the direction variable
var direction = ( that.sortUp ) ? 1 : -1;
// Define the function that compares the rows
var compareColumnValues = function (rowA, rowB) {
var valueA, valueB;
var i, cell;
// Get the cell value for row A
var cellsA = rowA.getElementsByTagName("td");
for ( i = 0; i < cellsA.length; i++ ) {
cell = cellsA[i];
if ( cell.className == that.sortColumn ) {
valueA = cell.firstChild.nodeValue;
break;
}
}
// Get the cell value for row B
var cellsB = rowB.getElementsByTagName("td");
for ( i = 0; i < cellsB.length; i++ ) {
cell = cellsB[i];
if ( cell.className == that.sortColumn ) {
valueB = cell.firstChild.nodeValue;
break;
}
}
// Convert the values to the appropriate data type
if ( ! isNaN(valueA) && ! isNaN(valueB) ) {
valueA = parseFloat(valueA);
valueB = parseFloat(valueB);
} else if ( isDate(valueA) && isDate(valueB) ) {
valueA = new Date(valueA);
valueB = new Date(valueB);
} else if ( isMoney(valueA) && isMoney(valueB) ) {
valueA = parseFloat(valueA.replace( /[$,]/g, "" ));
valueB = parseFloat(valueB.replace( /[$,]/g, "" ));
}
// Compare the two values and return the appropriate comparison value
if ( valueA < valueB ) {
return -1 * direction;
} else if ( valueB < valueA ) {
return 1 * direction;
} else {
return 0;
}
}
// Use the compareColumnValues function to sort the rows array
rows.sort( compareColumnValues );
// Add all rows back to the DOM
for ( i = 0; i < rows.length; i++) {
tbodyNode.appendChild( rows[i] );
}
}
You could use a bit more structure in your HTML markup to help your code figure out what can be sorted.
Put the totals row in a tfoot element and the sortable rows in a tbody element ... now you can target the sortable rows e.g.
var sortableRows = this.table.getElementsByTagName('tbody'),
rowNodes = sortableRows.getElementsByTagName('tr');
Update: Since you can't change the markup, remove the last row from your sorting array and cache it.
...
// Remove the header row from the array (but not the DOM)
rows.shift();
// And now we remove the footer row and cache it
var footerRow = rows.pop();
and then modify your code to write the sorted rows back to the DOM using insertBefore
...
// Add all rows back to the DOM, before the footer row
for ( i = 0; i < rows.length; i++) {
tbodyNode.insertBefore(rows[i], footerRow);
}
That loop is actually a bit of a performance problem, since you're making multiple writes to the DOM. It would be better to write all those sorted nodes to a documentFragment and just write to the DOM once, as follows:
...
var sortedFragment = document.createDocumentFragment();
// Write all the sorted rows to a fragment
for ( i = 0; i < rows.length; i++) {
sortedFragment.appendChild(rows[i]);
}
// Insert fragment containing sorted rows before footer
tbodyNode.insertBefore(sortedFragment, footerRow);
I found a great solution, which I actually used in code for my job! I can't take the credit for it however, but I just wanted to point y'all in the right direction:
http://www.kryogenix.org/code/browser/sorttable/
"1. Download the Javascript library here: http://www.kryogenix.org/code/browser/sorttable/sorttable.js
2.Include the Javascript library, by putting a link to it in the HEAD of your page, like so:
3.Mark your table as a sortable one by giving it a class of "sortable":
Note that the library's JavaScript file is called sorttable (two Ts), but the class you add to the table is sortable (one T)."
The setup is pretty straightforward and should allow for both ascending and descending sorts. Let me know if you have any questions.
Thanks! Paul

How to prevent Javascript updating entire control, and refreshing content?

I have this code:
function addFormControls() {
var e = document.getElementById("ProductsList");
var prodid = e.options[e.selectedIndex].value;
var prodvalue = e.options[e.selectedIndex].text;
if (num == 0) {
document.getElementById("ProductsPanel").innerHTML = '<h3>Products added to Variant</h3>';
}
if (num < 10) {
var boolCheck = checkArrayData(prodid);
if (boolCheck == false) {
document.getElementById("ProductsPanel").innerHTML = document.getElementById("ProductsPanel").innerHTML + prodvalue + '<input type="text" id="' + prodid + 'product" value="0" width="50px" maxlenght="2" /><input type="button" onclick="updateArrayData(\'' + prodid + '\', document.getElementById(\'' + prodid + 'product\').value);" value="Update Number" /><br />';
num++;
prodIdArray.push({
'key': prodid,
'value': prodvalue,
'num': 0
});
document.getElementById("productsArray").value = prodIdArray;
} else {
alert("Sorry product has already been added!");
}
}
}
which happily updates a div tag with new info, however if you look at the section where it prints a text box to the screen, line 13, these textbox's will be updated by the user.
So in short, textboxs are added, and value update.
however if there is a textbox with value 5, then this function called again to add another textbox, the previous textbox' values will be wiped clean!
So, how do i prevent this, will i have to do some, for loop over div controls taking the values, then put them back after this function is called?!?
I create some javascript to save all the values in a particular input's value field before adding the control, then return all the saved values back to their respected inputs.
function saveValuesOfProducts()
{
// initialise the array
numOfProds = new Array();
// get all the elements which are inputs
var x=document.getElementsByTagName("input");
// remove all un necessary inputs
x = leaveTextInputs(x);
// loop through the entire list of inputs left saving their value
for (i=0; i<x.length; i++)
{
numOfProds.push(x[i].value);
}
}
function returnValuesOfProducts()
{
// get all the elements which are inputs
var x=document.getElementsByTagName("input");
// remove all un necessary inputs
x = leaveTextInputs(x);
// loop through the entire list of saved values and return them to the input
for (i=0; i<numOfProds.length; i++)
{
x[i].value = numOfProds[i];
}
}
function leaveTextInputs(value)
{
// create a new blank array
var newArr = new Array();
// loop through all the elements in passed array
for (i=0; i<value.length; i++)
{
// cache the element
var thevalue = value[i];
// check if the element is a text input
if (thevalue.type == "text")
{
// check the id consists of product in it!
var regexteststring = thevalue.id;
// create the pattern to match
var patt1 = /product/i;
if (regexteststring.match(patt1) == "product")
{
// as additional check, if it has a size quantity of 2 then its defo out stuff
if (thevalue.size == 2)
{
newArr.push(thevalue);
}
}
}
}
// now return the new array
return newArr;
}

Categories

Resources