Replaceing column content with image doesnt work. It only replaces last - javascript

LOOK at the image PLEASE
There is a table that is refreshing every second with AJAX. 2nd column of table has 0 or 1 inside. I want to replace 0 with one image and 1 with another image. Currently I am looping through all the rows but only last row of one kindof image is filled in. All row shoul have a picture in them. What am I doing wrong?
var warningImg = document.createElement("IMG");
warningImg.src = "icone/ic_warning.png";
var okImg = document.createElement("IMG");
okImg.src = "icone/ic_done.png";
$(document).ready(function(){
$.ajaxSetup({ cache: false });
setInterval(function() {
$.get("IOdoc.htm", function(result){
var stringArray = result.trim().split(",");
$('#safety tr:eq(0) td:eq(1)').text(stringArray[0]);
$('#safety tr:eq(1) td:eq(1)').text(stringArray[1]);
$('#safety tr:eq(2) td:eq(1)').text(stringArray[2]);
var safetyEls = document.querySelectorAll("#safety tr td:nth-child(2)");
for(var i=0; i < safetyEls.length ; i++){
if (safetyEls[i].innerHTML.trim() == "1")
{
safetyEls[i].appendChild(okImg);
}
else{
safetyEls[i].appendChild(warningImg);}
}
});
},1000);
});
I tried something that proves that for loop is working. I replaced appendChild with textContent just wrote some text.
safetyEls[i].textContent = "Warning"
This worked. Working table just with text

Each time you call the appendChild, you move the image you have created.
Try cloning it to create new image for each row:
if (safetyEls[i].innerHTML.trim() == "1")
{
safetyEls[i].appendChild(okImg.cloneNode(true));
}
else{
safetyEls[i].appendChild(warningImg.cloneNode(true));}
}
For more details see http://www.w3schools.com/jsref/met_node_clonenode.asp

Related

EditableGrid - How to make every column header into individual filter

I am using EditableGrid (http://www.editablegrid.net/) Which creates some nice looking Editable tables
I'm Trying to modify the table header to make them into Individual filters like in example - https://phppot.com/demo/column-search-in-datatables-using-server-side-processing/
Current Filter textbox works very nicely but has a limit for searching one value for all columns.
I find many solutions for an individual column filter but I don't want to use other tables as they do not provide inline table editing functionality with dropdown and date picker, Is there a way I can implement it in EditableGrid?
I have also Asked this Question on Github (https://github.com/webismymind/editablegrid-mysql-example/issues/66) but the thread is not been active for a long time so I have very little hope of getting a solution from there.
In index.html update this code: see where //new code ---- starts and //new code ---- ends, try it out..
<script type="text/javascript">
var datagrid;
window.onload = function() {
datagrid = new DatabaseGrid();
//new code ---- starts
var list = document.getElementsByTagName("thead")[0];
for(var i = -1; i < list.childNodes.length; i++){
var input = document.createElement("input");
input.type = "text";
input.className = "filter";
list.getElementsByTagName("th")[i+1].appendChild(input);
}
var z = document.getElementsByClassName('filter')
for(var i = 0; i< z.length; i++){
z[i].addEventListener("input", function(e){
datagrid.editableGrid.filter( e.target.parentNode.querySelector("input").value, [i]);
})
}
//new code ---- ends
// key typed in the filter field
$("#filter").keyup(function() {
datagrid.editableGrid.filter( $(this).val());
// To filter on some columns, you can set an array of column index
//datagrid.editableGrid.filter( $(this).val(), [0,3,5]);
});
$("#showaddformbutton").click( function() {
showAddForm();
});
$("#cancelbutton").click( function() {
showAddForm();
});
$("#addbutton").click(function() {
datagrid.addRow();
});
}
$(function () {
});
</script>

Search table cell text against array

I have a table with a bunch of data in it. Currently, my code compares textfield input to the data in the table. If there's a match, it will show that particular table row. Here's my code:
$(document).on('keyup','#filterText',function(){
$('.all').hide(); // hide everything
$('tfoot').hide(); // hide everything
var s = $(this).val().toLowerCase(); //get input string
if(s==''){$('.all').show(); $('tfoot').show();}; // if no input then show everything
$('#report tbody tr td').each(function(i,td) {
//go through each table cell and compare
if($(td).text().toLowerCase().indexOf(s)!==-1){
$(td).closest('tr').show(); // show table row
}
});
}); //.but_filterText
This works great. But now, I need to modify this so that a user could do multiple searches at the same time, separated by a comma. So here's what I did and nothing happens:
$(document).on('keyup','#filterText',function(){
$('.all').hide();
$('tfoot').hide();
var s = $(this).val().toLowerCase().split(',');
if(s === undefined || s.length == 0){
$('.all').show(); $('tfoot').show();
};
$('#report tbody tr td').each(function(i,td) {
if(s.indexOf($(td).text().toLowerCase())!==-1){
$(td).closest('tr').show();
}
});
}); //.but_filterText
Seems like it should work but can't get it going. What am I doing wrong. Thank you
I thinks the issue is because in the input field you type space after comma, e.g. text 1, text 2 instead of text 1,text 2
i made a small (similar to yours code) example: (in this example you can type with or without space, since it will be replaced)
$('[name="search"]').on('keyup', function() {
var $tds = $('td');
var s = this.value.toLowerCase().replace(/\,\s/,',').split(',');
// consider replacing comma+space (/\,\s/) with just a comma
// and also i would recommend using filter function for finding matches,
// it will return an array of matched elements, empty if there is no match
$tds = $tds.filter(function(i, td) {
return s.indexOf($(td).text().toLowerCase()) >=0;
});
$tds.addClass('selected');
});
Here is the jsfillde - http://jsfiddle.net/zqdbso1w/1/
UPDATE (based on your comment)
Here is the jsfillde - http://jsfiddle.net/zqdbso1w/3/
simply make second iteration to seek for a substring in haystack
$('[name="search"]').on('keyup', function() {
var $tds = $('td');
var s = this.value.toLowerCase().replace(/\,\s/,',').split(',');
$tds.removeClass('selected');
$tds.each(function() {
var text = $(this).text().toLowerCase();
var r = s.filter( function(t) {
if (!t.length) return false;
return text.indexOf(t) >= 0;
});
if (r.length) $(this).addClass('selected');
});
});
UPDATE regex should be global, and remove all spaces after all commas
Here is the jsfiddle - http://jsfiddle.net/zqdbso1w/4/

How to give a unique id for each cell when adding custom columns?

I wrote following code to add a custom column to my table. but i want to add a unique id to each cell in those columns. the format should be a(column no)(cell no>)
ex :- for the column no 4 :- a41, a42, a43, ........
So please can anyone tell me how to do that. Thank You!
$(document).ready(function ()
{
var myform = $('#myform'),
iter = 4;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
var colName = $("#txtText").val();
if (colName!="")
{
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td>'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
}
});
iter += 1;
});
});
You seem to have code that's modifying the contents of the table (adding cells), which argues fairly strongly against adding an id to every cell, or at least one based on its row/column position, as you have to change them when you add cells to the table.
But if you really want to do that, after your modifications, run a nested loop and assign the ids using the indexes passed into each, overwriting any previous id they may have had:
myform.find("tr").each(function(row) {
$(this).find("td").each(function(col) {
this.id = "a" + row + col;
});
});
(Note that this assumes no nested tables.)
try this
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'">'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'"><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
you just have to define and iterate the column_no and cell_no variable
When all other cells are numbered consistently (for example using a data-attribute with value rXcX), you could use something like:
function addColumn(){
$('table tr').each(
function(i, row) {
var nwcell = $('<td>'), previdx;
$(row).append(nwcell);
previdx = nwcell.prev('td').attr('data-cellindex');
nwcell.attr('data-cellindex',
previdx.substr(0,previdx.indexOf('c')+1)
+ (+previdx.substr(-previdx.indexOf('c'))+1));
});
}
Worked out in this jsFiddle

javascript loop through li in div of paginate

Below is the code I'm using. The top part $('div.pagination... works fine, I can alert(length) and it gives me the correct value of pages in the pagination section. The bottom part appears not to work. This is for a scraper that will open each page on a forum. If I leave the loop out of it it successfully retreaves the url for page here. The length -=2 is to remove the next/previous li from the total count.
$('div.pagination').each(function() {
var length = $(this).find('li').length;
length -= 2;
});
for (var i = 0; var <= length; i++) {
var pageToOpen = 'http://someWebsite.com/index/page:' + i;
alert(pageToOpen);
page.open(pageToOpen, function (status) {
if (status == 'success') {
logAuctions();
}
}});
}
Define your var length outside (before) the.each()
Using .lentgh method you might miss the real page indexes. So I would suggest to grab the real anchor hrefs.
FIDDLE DEMO
var pages = [];
// skipping the "Next" and "Last" get all A ahchors
$('div.pagination li').slice(0,-2).find('a').each(function(){
pages.push( $(this).attr('href') );
});
$.each(pages, function(i, v){
$('<div>'+ ("http://someWebsite.com"+v) +'</div>').appendTo('#output');
});
/* WILL RESULT IN:
http://someWebsite.com/auctions/index/page:2
http://someWebsite.com/auctions/index/page:3
http://someWebsite.com/auctions/index/page:4
*/

Creating Table from Google Spreadsheets: How to Manipulate Data?

Currently, I'm working on a project to pull data from a Google Form/Spreadsheet and have it appear on a website using JQuery/DataTables. I had received help on getting the data to appear on the site, but I've hit a new issue.
Previous Question: Is it possible to create a public database (spreadsheet) search with Google Scripts?
On Google, I have a form which outputs eight columns:
Timestamp
Title
Author
Type
URL
Topic(s)
Country(s)
Tages
Of these, I don't need the timestamp to appear, and I would like the title to link to the URL if the URL exists. Since I'm not quite fluent with Javascript or DataTables, I made a second sheet which I tried to simplified it down to the following six:
Title (currently being formatted as an <a> tag using the URL)
Author
Type
Topic(s)
Country(s)
Tages
This almost works, except that the script I'm using to construct the table renders the Title field as it is in the cell with the being visible in the table. See the table under the title "Actual Output" for the current situation; the table under "Target Table Appearance" is what I'm aiming for.
Current Output: http://interculturalresources.weebly.com/webtest.html
Table Creation Script: http://www.weebly.com/uploads/1/7/5/3/17534471/tablescript.js
Thus, is there a way to have the be given as a link despite being put together in a Google Spreadsheet cell? Alternatively, is there a way to edit the current script to a) ignore the timestamp column and b) make the Title output a link to the URL from the URL column (with proper conditionals)?
EDIT: I'm focusing on the links now; I have a solution for the timestamp which involves copying the data to a new spreadsheet (since forms are strict with copy/pasting information). The current issue is getting each entry to have a link assuming the URL is in the first column, and the Title is in the second column. Please read Mogsdad's answer and my first comment for more information.
Solution: First, my thanks to Mogsdad for the "spark" of inspiration and insight which led me in the correct direction towards the solution. To explain the general idea, I wanted to not display one column (URL) from a Google Spreadsheet on the target website, yet use it's content to create a link in another (Title). Then, once the table was made, DataTables is used to format it. All cells in the table must contain something, so if the cell is to be blank, it must be filled with "None".
function cellEntries(json, dest, divId) {
var table = document.createElement('table');
table.setAttribute("id", divId + "table"); //Assign ID to <table> from the <div> name.
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
var thr;
var tr;
var entries = json.feed.entry;
var cols = json.feed.gs$colCount.$t; //The number of columns in the sheet.
var link; //Teporary holder for the URL of a row.
for (var i=0; i <cols; i++) { //For the first row of cells (column titles),
var entry = json.feed.entry[i];
if (entry.gs$cell.col == '1') { //For First Column / URL Column, (1)
if (thr != null) {
tbody.appendChild(thr);
}
thr = document.createElement('tr'); //Create <thr>/<tr> (???).
}
else { //For all other columns,
var th = document.createElement('th');
th.appendChild(document.createTextNode(entry.content.$t)); //Create title for each column.
thr.appendChild(th);
}
}
for (var i=cols; i < json.feed.entry.length; i++) { //For all remaining cells,
var entry = json.feed.entry[i];
if (entry.gs$cell.col == '1') { //For First Column / URL Column, (1)
if (tr != null) {
tbody.appendChild(tr);
}
tr = document.createElement('tr'); //Create <tr>.
hlink = entry.content.$t; //Put URL content into hlink.
}
else if (entry.gs$cell.col == '2') { //For Title Column,(2)
var td = document.createElement('td');
if (hlink != "None") { //If there is a link,
var alink = document.createElement('a'); //Make <a>
alink.appendChild(document.createTextNode(entry.content.$t)); //Put content in <a>
alink.setAttribute('href',hlink); //Assign URL to <a>.
td.appendChild(alink); //Put <a> in <td>.
}
else { //If there is no link,
td.appendChild(document.createTextNode(entry.content.$t)); //Put content in <td>.
}
tr.appendChild(td);
}
else { //For all other columns,
var td = document.createElement('td');
if (entry.content.$t != "None") { //If content is not "None",
td.appendChild(document.createTextNode(entry.content.$t)); //Output the content.
}
else { //Else,
td.appendChild(document.createTextNode("")); //Output a blank cell.
}
tr.appendChild(td);
}
}
$(thead).append(thr);
$(tbody).append(tr);
$(table).append(thead);
$(table).append(tbody);
$(dest).append(table);
$(dest + "table").dataTable();
};
function importGSS(json){
var divId = "targetdivid" //ID of the target <div>.
cellEntries(json, "#" + divId, divId);
};
Around this bit in tablescript.js:
var th = document.createElement('th');
th.appendChild(document.createTextNode(entry.content.$t));
>>>>
thr.appendChild(th)
You can add a hyperlink by doing this:
th.setAttribute('href',<link>);
...with <link> set to the hyperlink for the particular publication.
To make this work, you could rework your spreadsheet source to have the link in one column, and the Title in another. Then modify tablescript.js to combine the link and text, something like this:
var hlink = null; // Temporary storage for hyperlink
for (var i=0; i <cols; i++) {
var entry = json.feed.entry[i];
if (entry.gs$cell.col == '1') {
if (thr != null) {
tbody.appendChild(thr);
}
thr = document.createElement('tr');
}
// Element 0 assumed to have hyperlink
if (i == 0) {
hlink = entry.content.$t;
}
else {
var th = document.createElement('th');
// If we have an hlink, set the href attribute.
if (hlink !== null) {
th.setAttribute('href',hlink);
hlink = null;
}
th.appendChild(document.createTextNode(entry.content.$t));
thr.appendChild(th);
}
}

Categories

Resources