Diaplaying unique element into the html table through JQuery - javascript

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:

Related

JS Adding/Removing image from cell (toggle button)

I am looking for a way to add and remove an image in a cell.
I have the button assigned to this function but I can't seem to add it to the dynamic range. If I hardcode the column and row for testing it adds the image fine but then I can't figure out how to delete it.
function test() {
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 CONTAINS IMAGE REMOVE IT
continue; // --> go to next cell
} else {
sheet.insertImage("URL", [col], [row], 125, 2); //Add image at col/row
}
}
ranges[i].setValues(data);
}
}
Before button click
After button click
Select new cells
After button click
I believe your goal is as follows.
When the script is run after the cells are selected, you want to put the image on the cell.
When the image is not put on the cell, you want to put the image on the cell.
When the image has already been put on the cell, you want to remove the image.
When the cell value is empty, you don't want to do anything.
In this case, how about the following modified script?
Modified script:
function test() {
const url = "###"; // Please set your URL.
const sheet = SpreadsheetApp.getActiveSheet();
const ranges = sheet.getActiveRangeList().getRanges();
let images = sheet.getImages();
ranges.forEach(r => {
const row = r.getRow();
const col = r.getColumn();
const numRows = r.getNumRows();
const numCols = r.getNumColumns();
for (let i = 0; i < numRows; i++) {
for (let j = 0; j < numCols; j++) {
if (sheet.getRange(row + i, col + j).isBlank()) continue;
const image = images.filter(e => {
const anchor = e.getAnchorCell();
return anchor.getRow() == row + i && anchor.getColumn() == col + j;
});
if (image.length > 0) {
image.forEach(e => e.remove());
images = sheet.getImages();
} else {
sheet.insertImage(url, col + j, row + i, 125, 2);
}
}
}
});
}
At first, please set your URL.
When you use this script, please select the cells and run the script.
When you run this script for the selected cells, the images are put on the cells which have no images, and the images are removed from the cells which have the images.
In this case, the image on the cells can be checked using the method of getAnchorCell() of Class OverGridImage.
References:
getImages() of Class Sheet
getAnchorCell() of Class OverGridImage

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

Number table rows in Google Doc using Apps Script

I'm working on a script which takes text and places each paragraph in a numbered table cell. I'm running into a problem where each line break is counted as a paragraph by the script, which means my table either has empty cells or is numbered incorrectly.
Here's the working script (minus row numbering):
function formatArticle() {
var doc = DocumentApp.getActiveDocument()
var body = doc.getBody();
// Get the paragraphs
var paras = body.getParagraphs();
// Add a table to fill in with copied content
var addTable = body.appendTable();
for (var i=0;i<paras.length;++i) {
// If the paragraph is text, add a table row and insert the content.
if(i % 2 == 0) {
var tr = addTable.appendTableRow();
var text = paras[i].getText();
// Number the table rows as they're added in a cell to the left.
for(var j=0;j<2;j++) {
if(j == 0) {
var td = tr.appendTableCell(i);
} else {
var td = tr.appendTableCell(text);
}
}
}
// Shrink left column.
addTable.setColumnWidth(0, 65);
// Delete the original text from the document.
paras[i].removeFromParent();
}
}
Here's a demo Google Doc so you can see how text formats without setting a new one up yourself if that helps.
Logic
What you should do is to iterate each paragraph and check if that paragraph contains text. If yes, then add a row and put the text in it, else skip that paragraph and jump to the next one.
Implementation
function formatArticle(){
var doc = DocumentApp.getActiveDocument()
var body = doc.getBody();
// Get the paragraphs
var paras = body.getParagraphs();
var addTable = body.appendTable();
//paragraph index
var pIndex = 0;
for(var i = 0 ; i < paras.length ; i++){
var para = paras[i];
var paraStr = para.editAsText().getText();
// if there is string content in paragraph
if(paraStr.length){
var tr = addTable.appendTableRow();
var td1 = tr.appendTableCell(pIndex);
var td2 = tr.appendTableCell(paraStr);
pIndex ++;
}
para.removeFromParent();
}
// Shrink left column.
addTable.setColumnWidth(0, 65);
}
Here You get the string from paragraph var paraStr = para.editAsText().getText(); and check if the content exists if(paraStr.length) If yes then create a row, insert paragraph index and paragraph's text in it.
Try this: tr.appendTableCell(i/2 +1)
// Number the table rows as they're added in a cell to the left.
for(var j=0;j<2;j++) {
if(j == 0) {
var td = tr.appendTableCell(i/2 +1);
} else {
var td = tr.appendTableCell(text);
}
}
}

Getting a text value from a specific table - Javascript

So I was able to find an specific table and I need to get no the text that's into the <b></b> of this table. Can't figure out how.
I'm using the following to test if I'm seeing my table correct:
var a = document.getElementsByTagName('table').length;
for (var i=0; i < a; i++)
{
b = document.getElementsByTagName("table")[i];
if (b.getAttribute("background") != null && b.getAttribute("background") == 'common/imgs/tabfade1.gif' ) { console.log(b.getAttribute("background")); }
}
result = true;
Any leads into how set my result as the text I need? Thanks in advance.
EDIT:
Image of the table.
Table Sample
document.querySelectorAll("table b")
Should give you a list of all <b> elements in all of the table elements.
Then you can peform your regular operations on them.
Well, in case someone else needs what I needed, here's what I've found as the solution:
var tables = document.getElementsByTagName('table');
var container = -1;
for (var i = 0; i < tables.length-1; i++) {
if (tables[i].background == "tabfade1.gif") {
container = i;
}
}
if (container > -1) {
result = tables[container].rows[0].cells[0].innerText.trim();
} else {
result = "";
}

Simulating CSS Column vertical content flow by re-ordering elements using jQuery?

I have an unordered list with approx 50 li elements that is displayed in a four column grid with the addition of media queries that change the column count at different widths.
To support IE8&9, I am using fallback CSS and Modernizr to float the li elements left and specify widths and margin which simulates the CSS Column layout.
The only difference is that the items flow horizontally rather than vertically.
I want to perform some sort of "grid sort" re-shuffling of the $('.main-index li') array so that that the li elements run in an order like 1,14,27,40,2,15,28,41,3... rather than 1,2,3,4,5,6,7,8...
I have not got far, but this is that start I've made...
if (!Modernizr.csscolumns) {
// If CSS Columns is not supported, re-order li elements
// instead of 1,2,3,4,5,6,7,8... reorder to 1,14,27,40,2,15,28,41,3...
var columnCount = $('.main-index li').css('column-count'); // = 4
var itemCount = $('.main-index li').length; // = 50
}
I've included a jsFiddle here that i'm using to test.
Is this good enough?
$( document ).ready(function() {
// If CSS Columns is not supported, re-order li elements
// instead of 1,2,3,4,5,6,7,8... reorder to 1,14,27,40,2,15,28,41,3...
var items = $('.main-index li');
var columnCount = $('.main-index ul').css('column-count'); // = 4
if ( typeof columnCount != 'number' ) {
columnCount = 4;
}
var itemCount = items.length; // = 5
function reflow() {
var rowCount = Math.ceil(itemCount / columnCount);
items.detach();
$('.main-index ul').empty(); // Prevent build-up of dummy items
for (var row = 0; row < rowCount; row++) {
for (var column = 0; column < columnCount; column++) {
var index = row + (column * rowCount);
if ( index >= itemCount ) {
$('.main-index ul').append('<li class="dummy">');
} else {
$('.main-index ul').append(items[index]);
}
}
}
}
$(window).on('resize', function() {
var newColumnCount = $('.main-index ul').css('column-count'); // = 4
if ( typeof newColumnCount != 'number' ) {
newColumnCount = 4;
}
if ( newColumnCount != columnCount ) {
columnCount = newColumnCount;
reflow();
}
});
});

Categories

Resources