Adding Select All checkbox in a new row after combining two tables - javascript

I have successfully implemented select all check box at the end of the row in case there is only one table to display. However in one of the tab I am combining two tables data and dividing them in two columns thus the number of rows are different in those two columns.
I am trying to figure out how to populate two different select all checkbox at the end of the rows in both columns.
I am populating tables dynamically using JS. Here is my code
HTML
<div id="tabs">
<ul id="betTypesTabs"></ul>
</div>
JS for populating the table data from two sources
function drawSelectionsForDoubles(table, events, indexes) {
// Array of Horse Selections for every event
var arrayOfSelections = [];
$.each(indexes, function (i, index) {
arrayOfSelections[i] = events[index].markets[0].selections;
});
// Max number of Selections
var maxNumberOfSelections = 0;
for (var i=0; i<arrayOfSelections.length; i++) {
if (arrayOfSelections[i].length > maxNumberOfSelections) maxNumberOfSelections = arrayOfSelections[i].length;
}
// Going through all the selections in the horizontal manner
for (var i=0; i<maxNumberOfSelections; i++) {
for (var j=0; j<arrayOfSelections.length; j++) {
var currentHorse = arrayOfSelections[j][i];
// If the horse exists
if (currentHorse != null) {
// If the horse is participating in Running Double bet
$.each(currentHorse.prices, function(index, value) {
if (value.betTypeId == 108) {
// Adding the record
// First tds in the row
if (j == 0) {
var tr = createTr(table.id + '_' + i, "white");
$(tr).append(createTd(null, null, currentHorse.position, null));
$(tr).append(createTd(null, null, currentHorse.name, null));
var td = createTd(null, null, "",null);
td.appendChild(createInput(table.id + '_' + i + "_doubles_" + currentHorse.id, table.id + "_doubles_1", "checkbox", null));
$(tr).append(td);
$(table).append(tr);
}
// Second column
else {
tr = document.getElementById(table.id + '_' + i);
if (tr == null) {
var tr = createTr(table.id + '_' + i, "white");
$(table).append(tr);
var td = createTd(null, null, '', 3);
$(tr).append(td);
}
$(tr).append(createTd(null, null, currentHorse.position, null));
$(tr).append(createTd(null, null, currentHorse.name, null));
var td = createTd(null, null, "",null);
td.appendChild(createInput(table.id + '_' + i + "_doubles_" + currentHorse.id, table.id + "_doubles_2", "checkbox", null));
$(tr).append(td);
}
}
});
}
}
}
}
Now since the rows in two columns are different I want to add an extra row after the table where I can add a checkbox which will select all the rows in the table.

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:

Insert text to selected range with button

I apologize in advance for having little to no knowledge on this matter. I am familiar enough to utilize VBA but have recently made the switch to Sheets and I am lost.
I was originally looking for a way to prompt a drop down menu when double clicking a cell in a range that will then add the selected information as a prefix to the text.
Example: cell contains "First Last", upon double clicking you get a drop down to select "Mr., Mrs." when selecting "Mr." the cell now says "Mr. First Last" but it doesn't appear that you can set a double click event.
So now I am trying to come up with another solution where you select desired cells and 'apply' the function.
Example: Select cells A1 B1 C3 D9, click a button that applies "Mr. " as a prefix. Selecting it again will remove it.
Please help me get this moving.
Try this:
// menu
function onOpen() {
SpreadsheetApp.getUi().createMenu('⚡ Scripts')
.addItem('🎩 Add Mr', 'add_Mr')
.addItem('Remove Mr', 'remove_Mr')
.addToUi();
}
// functions
function add_Mr() {
var sheet = SpreadsheetApp.getActiveSheet();
var selection = sheet.getSelection();
var ranges = selection.getActiveRangeList().getRanges();
for (var i in ranges) {
var data = ranges[i].getValues();
for (var row in data) for (var col in data[row])
if (data[row][col] != '') data[row][col] = 'Mr. ' + data[row][col];
ranges[i].setValues(data);
}
}
function remove_Mr() {
var sheet = SpreadsheetApp.getActiveSheet();
var selection = sheet.getSelection();
var ranges = selection.getActiveRangeList().getRanges();
for (var i in ranges) {
var data = ranges[i].getValues();
for (var row in data) for (var col in data[row])
if (data[row][col] != '') data[row][col] = data[row][col].replace(/^Mr\. /,'');
ranges[i].setValues(data);
}
}
It will add menu Scripts and two commands 'Add Mr' and 'Remove Mrs' for selected cells.
And as a homework you can try to add add_Mrs() and remove_Mrs() functions.
If you need to toggle 'Mr' here you go:
function toggle_Mr() {
var sheet = SpreadsheetApp.getActiveSheet();
var selection = sheet.getSelection();
var ranges = selection.getActiveRangeList().getRanges();
for (var i in ranges) {
var data = ranges[i].getValues();
for (var row in data) for (var col in data[row]) {
var cell = data[row][col];
if (cell == '') continue; // if empty --> go to next cell
if (cell.match(/^Mr\. /)) { // if contains 'Mr.'
data[row][col] = cell.replace(/^Mr\. /,''); // --> remove 'Mr.'
continue; // --> go to next cell
} else {
data[row][col] = 'Mr. ' + data[row][col]; // else --> add 'Mr.'
}
}
ranges[i].setValues(data);
}
}
Update
Here is the same function toggle_Mr() with example how you can get the 'coordinates' of all processed cells:
function toggle_Mr() {
var sheet = SpreadsheetApp.getActiveSheet();
var selection = sheet.getSelection();
var ranges = selection.getActiveRangeList().getRanges();
for (var i in ranges) {
// get 'coordinates' (col, row) of first (left-top) cell of selected range
var start_col = ranges[i].getColumn();
var start_row = ranges[i].getRow();
var data = ranges[i].getValues();
for (var row in data) for (var col in data[row]) {
var cell = data[row][col];
// calculate the real 'coordinates' of processed cells
var real_col = +start_col + +col;
var real_row = +start_row + +row
console.log('Process the cell [' + real_col + '][' + real_row + ']');
if (cell == '') continue;
if (cell.match(/^Mr\. /)) {
data[row][col] = cell.replace(/^Mr\. /,'');
continue;
} else {
data[row][col] = 'Mr. ' + data[row][col];
}
}
ranges[i].setValues(data);
}
}
You can see the cell 'coordinates' in console if you run the function from the Script Editor.

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

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

.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 dynamic table in jquery

Sorry but I'm completly new to js and jquery.
I got dynamic table which values are in localstorage. I can add new row, delete row, and edit cells. This is working.
I want to add a sorting this table by clicked colum. I found here code and try it. It just working when I write table and not use my javascript to add rows from localstorage. Table in two cases looks same in html code. I have no idead why sorting isnt working with dynamic table.
This is w/o my dynamic table from localstore, sorting as supposed to:
http://jsfiddle.net/eW8Kg/1/
This is with table from localstorage(not working in jsfiddle?) on my comupter this is working good, but table is not sorting! (I left this static values):
http://jsfiddle.net/XAu5G/
I think my problem can be in creation of table content:
var Html = "<tbody>";
for (var i = 1; i < localStorage.length; i++) {
var input = "<td><input style='border:hidden' class=\"fields\" name = " + localStorage.key(i) + " type='text' onchange='change(\"" + localStorage.key(i) + "\")' /></td>"
Html += "<tr class=\"field\">";
for (var j = 0; j < 4; ++j) {
Html += input;
}
var button = "<td><input type='button' value = 'Usuń' onclick='Remove(\"" + localStorage.key(i) + "\")'></td>";
Html += button + "</tr>";
}
Html += "<tr id=\"actions\"></tr></tbody>"
document.getElementById("list").innerHTML += Html;
This jquery code do sorting:
$(document).ready(function() {
var table = $('#list');
jQuery.fn.sortElements = (function() {
var sort = [].sort;
return function(comparator, getSortable) {
getSortable = getSortable || function() {return this;};
var placements = this.map(function() {
var sortElement = getSortable.call(this),
parentNode = sortElement.parentNode,
// Since the element itself will change position, we have
// to have some way of storing it's original position in
// the DOM. The easiest way is to have a 'flag' node:
nextSibling = parentNode.insertBefore(
document.createTextNode(''),
sortElement.nextSibling
);
return function() {
if (parentNode === this) {
throw new Error(
"You can't sort elements if any one is a descendant of another."
);
}
// Insert before flag:
parentNode.insertBefore(this, nextSibling);
// Remove flag:
parentNode.removeChild(nextSibling);
};
});
return sort.call(this, comparator).each(function(i) {
placements[i].call(getSortable.call(this));
});
};
})();
$('#x').click(function(){
$('#list').hide();
});
$('#nazwa-header').wrapInner('<span title="sort this column"/>').each(function() {
var th = $(this),
thIndex = th.index(),
inverse = false;
th.on('click', function() {
table.find('td').filter(function() {
return $(this).index() === thIndex;
}).sortElements(function(a, b) {
console.log($(a).find('input').val(),$(b).find('input').val());
return $(a).find('input').val() > $(b).find('input').val() ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}, function() {
// parentNode is the element we want to move
return this.parentNode;
});
inverse = !inverse;
});
});
});

Categories

Resources