I have this in Jquery all works:
$(document).ready(function() {
$("#checktable td:nth-child(1)").click(function(event){ // This line I need converted
event.preventDefault();
var $td = $(this).closest('tr').children('td'); //This line I need converted
var tid = $td.eq(0).text();
var tdate = $td.eq(1).text();
var tdescribe = $td.eq(2).text();
var wd = $td.eq(3).text();
var dep = $td.eq(4).text();
// ... more code
I need a similar thing in javascript, above only first td is clicked.
My javascript code so far:
function addRowHandlers() {
var table = document.getElementById("checktable2");
var rows = table.getElementsByTagName('tr');
var tid = '';
var tdate = '';
var tdescribe = '';
var wd = '';
var dep = '';
var tisclr = '';
for (var i = 1; i < rows.length; i++) {
rows[i].i = i;
rows[i].onclick = function() {
tid = table.rows[this.i].cells[0].innerText;
tdate = table.rows[this.i].cells[1].innerHTML;
tdescribe = table.rows[this.i].cells[2].innerHTML;
wd = table.rows[this.i].cells[3].innerHTML;
dep = table.rows[this.i].cells[4].innerHTML;
// ... etc more code
The javascript works but any td can be clicked, I am after only:
The first td clicked
Then get parent row
Then all child td's
I have been over dozens of StackOverflow posts and other sites as well... Thanks
And how do I add the event.preventDefault() to regular JS in such a case.
You'd bind the handler to the first .cell.
rows[i].cells[0].onclick = function () {
And then in the handler, access the .parentNode of this to get the row.
And since you're not closing over any variables except those in the function itself (and outside that function, of course), I'd just use a single handler instead of recreating it in the loop.
function addRowHandlers() {
var table = document.getElementById("checktable2");
var rows = table.getElementsByTagName('tr');
var tid = '';
var tdate = '';
var tdescribe = '';
var wd = '';
var dep = '';
var tisclr = '';
for (var i = 1; i < rows.length; i++) {
rows[i].i = i;
rows[i].cells[0].onclick = handler;
}
function handler() {
var row = this.parentNode;
tid = this.innerText;
tdate = row.cells[1].innerHTML;
tdescribe = row.cells[2].innerHTML;
wd = row.cells[3].innerHTML;
dep = row.cells[4].innerHTML;
// etc more code
}
}
I'd probably use a loop to get the desired content too. Maybe like this:
function handler() {
var row = this.parentNode;
var props = ["tid", "tdate", "tdescribe", "wd", "dep"];
var content = props.reduce(function(obj, key, i) {
obj[key] = row.cells[i][i ? "innerHTML" : "innerText"];
return obj;
}, {});
// etc more code
}
Now instead of variables, you have properties of the content object.
Related
I have a loop in which I am calling rec_append() recursively, apparently the first pass alone works, then the loop stops.
I have an array of 4 elements going into that $.each loop but I see only the first element going into the function recursively. Help!
I switched it for a element.forEach but that gives me only the second element and I am stuck, is there a better solution to process a tree of elements? My array is a part of a tree.
var data = JSON.parse(JSON.stringify(result))
var graph = $(".entry-point");
function rec_append(requestData, parentDiv) {
var temp_parent_details;
$.each(requestData, function (index, jsonElement) {
if (typeof jsonElement === 'string') {
//Element construction
//Name and other details in the form of a : delimited string
var splitString = jsonElement.split(':');
var details = document.createElement("details");
var summary = document.createElement("summary");
summary.innerText = splitString[0];
details.append(summary);
temp_parent_details = details;
parentDiv.append(details);
var kbd = document.createElement("kbd");
kbd.innerText = splitString[1];
summary.append(' ');
summary.append(kbd);
var div = document.createElement("div");
div.className = "col";
details.append(div);
var dl = document.createElement("dl");
div.append(dl);
var dt = document.createElement("dt");
dt.className = "col-sm-1";
dt.innerText = "Path";
div.append(dt);
var dd = document.createElement("dd");
dd.className = "col-sm-11";
dd.innerText = splitString[2];
div.append(dd);
var dt2 = document.createElement("dt");
dt2.className = "col-sm-1";
dt2.innerText = "Type";
div.append(dt2);
var dd2 = document.createElement("dd");
dd2.className = "col-sm-11";
dd2.innerText = splitString[1];
div.append(dd2);
} else {
$.each(jsonElement, function (jsonElementArrIndx, jsonChildElement) {
rec_append(jsonChildElement, temp_parent_details); //Only 1 pass works, rest skip
});
}
});
}
rec_append(data, graph);
Sample data:enter image description here
This code below is a javascript code to change texts and background properties from the body tag at the same time when the browser is clicked. I've just followed rules in w3school.com, actually, I'm doing the same as the examples do, but mine won't work and I've failed to find my fault. plz, help me.
var helloDiv = document.createElement("div");
var helloText = document.createTextNode("hi.");
helloDiv.appendChild(helloText);
var bodyntext = document.getElementsByTagName("body").appendChild(helloDiv);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[0]+complementary[1]+complementary[2]).toString(16);
body.style.backgroundColor = "#"+ number.toString();
bodyntext.style.color = "#"+ clnumber.toString();
}
Here's your problem
var bodyntext = document.getElementsByTagName("body").appendChild(helloDiv);
Please note that the javascript functions that have plural names often return arrays which is the case here
document.getElementsByTagName("body") returns an array and you are trying to perform an invalid action, that is append child, to this array. You need to access an element using index and then perform this action.
so using
var bodyntext = document.getElementsByTagName("body")[0].appendChild(helloDiv); should fix your problem.
Use document.getElementsByTagName("body")[0] to achieve expected result, as getElementsByTagName() method returns a collection of all elements in the document with the specified tag name, as a NodeList object.
var helloDiv = document.createElement("div");
var helloText = document.createTextNode("hi.");
helloDiv.appendChild(helloText);
var bodyntext = document.getElementsByTagName("body")[0].appendChild(helloDiv);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[0]+complementary[1]+complementary[2]).toString(16);
body.style.backgroundColor = "#"+ number.toString();
bodyntext.style.color = "#"+ clnumber.toString();
}
codepen - https://codepen.io/nagasai/pen/NLBXJE
Please refer this link for more details - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName
I just change appendChild to document.body.appendChild(helloDiv) and added ID attribute for that div:
var helloDiv = document.createElement("div");
helloDiv.id = "myDIV";
document.body.appendChild(helloDiv);
var helloText = document.createTextNode("Click me");
helloDiv.appendChild(helloText);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
var helloText = document.getElementById("myDIV");
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[6]+complementary[1]+complementary[2]).toString(16);
var clnumber2 = (complementary[0]+complementary[2]+complementary[6]).toString(11);
body.style.backgroundColor = "#"+ number.toString();
helloText.style.color = "#"+number.toString();
}
I'm getting HTML from a forum url, and parsing the post count of the user from their profile page. I don't know how to write the parsed number into the Google spreadsheet.
It should go account by account in column B till last row and update the column A with count.
The script doesn't give me any errors, but it doesn't set the retrieved value into the spreadsheet.
function msg(message){
Browser.msgBox(message);
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Update")
.addItem('Update Table', 'updatePosts')
.addToUi();
}
function getPostCount(profileUrl){
var html = UrlFetchApp.fetch(profileUrl).getContentText();
var sliced = html.slice(0,html.search('Posts Per Day'));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
return postCount;
}
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var accountSheet = spreadSheet.getSheetByName("account-stats");
var statsLastCol = statsSheet.getLastColumn();
var accountCount = accountSheet.getLastRow();
var newValue = 0;
var oldValue = 0;
var totalNewPosts = 0;
for (var i=2; i<=accountCount; i++){
newValue = parseInt(getPostCount(accountSheet.getRange(i, 9).getValue()));
oldValue = parseInt(accountSheet.getRange(i, 7).getValue());
totalNewPosts = totalNewPosts + newValue - oldValue;
accountSheet.getRange(i, 7).setValue(newValue);
statsSheet.getRange(i,statsLastCol).setValue(newValue-todaysValue);
}
if(showAlert==false){
return 0;
}
msg(totalNewPosts+" new post found!");
}
function valinar(needle, haystack){
haystack = haystack[0];
for (var i in haystack){
if(haystack[i]==needle){
return true;
}
}
return false;
}
The is the first time I'm doing something like this and working from an example from other site.
I have one more question. In function getPostCount I send the function profileurl. Where do I declare that ?
Here is how you get the URL out of the spreadsheet:
function getPostCount(profileUrl){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var thisSheet = ss.getSheetByName("List1");
var getNumberOfRows = thisSheet.getLastRow();
var urlProfile = "";
var sliced = "";
var A_Column = "";
var arrayIndex = 0;
var rngA2Bx = thisSheet.getRange(2, 2, getNumberOfRows, 1).getValues();
for (var i = 2; i < getNumberOfRows + 1; i++) { //Start getting urls from row 2
//Logger.log('count i: ' + i);
arrayIndex = i-2;
urlProfile = rngA2Bx[arrayIndex][0];
//Logger.log('urlProfile: ' + urlProfile);
var html = UrlFetchApp.fetch(urlProfile).getContentText();
sliced = html.slice(0,html.search('Posts Per Day'));
var postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
Logger.log('postCount: ' + postCount);
A_Column = thisSheet.getRange(i, 1);
A_Column.setValue(postCount);
};
}
You're missing var in front of one of your variables:
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
That won't work. Need to put var in front. var postCount = ....
In this function:
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
There is no array named arguments anywhere in your code. Where is arguments defined and how is it getting any values put into it?
I have this for loop that gets the id and text of parents elements:
for (var i = 1; i < parents_num; i++)
{
var prev_parent_text = jQuery(id).parent().parent().find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').attr('id');
}
What I am trying to do is to increase the number of parent() by 2 in each loop:
For example,
for i = 1:
var prev_parent_text = jQuery(id).parent().parent().find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').attr('id');
for i = 2:
var prev_parent_text = jQuery(id).parent().parent().parent().parent().find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').parent('ul').parent('li').attr('id');
for i = 3:
var prev_parent_text = jQuery(id).parent().parent().parent().parent().parent().parent().find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').parent('ul').parent('li').parent('ul').parent('li').attr('id');
and so on..
I have used the eq() function unsuccesfully:
var num = (i*2) - 2
var prev_parent_text = jQuery(id).parent().eq(num).find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').eq(num).attr('id');
Thank you for any help
Keep a reference for each, and update the reference for each step:
var $id = jQuery(id);
var $li = jQuery(id);
for (var i = 1; i < parents_num; i++) {
$id = $id.parent().parent();
$li = $li.parent('ul').parent('li');
var prev_parent_text = $id.find('> .myclass').text();
var prev_parent_id = $li.attr('id');
}
You could add a custom jquery function for that, like this:
$.fn.nparent = function(n) {
var elem = $(this);
for (var i=0;i<n;i++) {
elem = elem.parent();
}
return elem;
}
And use it like:
var id = $('#element').nparents(4).attr('id');
I need to know how create a simple menu with 2 menu items(A and B): the first one(A) contains 1 item (A1),the second one(B), contains 3 items inside(B1,B2,B3)
I can create an example but always fail:
CODE
var handler = app.createServerHandler();
//Create menu bar
var menuBar = app.createMenuBar(true);
var data = ss.getSheets()[LOG_SHEET_INDEX].getDataRange().getValues();
var lastRow = ss.getLastRow();
for(var row = 1; row < lastRow; row++){
var id_menu =1;
if(data[row][0]==0){
var nivel = data[row][1];
var menuItem = app.createMenuItem(data[row][2], handler);
var separator = app.createMenuItemSeparator();
menuBar.addSeparator(separator);
var subMenu = app.createMenuBar(true).setId("subMenu"+nivel);
for(var i = 1; i< lastRow; i++){
if(data[i][0]==nivel){
var sm = app.getElementById("subMenu"+nivel)
this[sm.addItem(data[row][2], handler)];
}
}menuItem.setSubMenu(sm);
}menuBar.addItem(data[row][2], app.createMenuBar(true));
}
app.add(menuBar);
RESULT
and i need something like (hidding A1,B1,B2,B3 : showing when focus A|B):
____
A
A1
____
B
B1
B2
B3
THIS IS MY SPREAD:
Please Help!!
Hmm, as Serge pointed out my prev. answer is wrong. Meanwhile I found out, what the real reason is:
The MenuItem having the submenu must not have a handler:
var menuBar=app.createMenuBar();
var subb1=app.createMenuBar(true);
subb1.addItem (app.createMenuItem("S1", handler1));
subb1.addItem (app.createMenuItem("S2", handler2));
var mi1=app.createMenuItem("X1", null); // passing null and not a handler makes submenu work...
mi1.setSubMenu(subb1);
menuBar.addItem(mi1);
app.add(menuBar);
I done it but I have a problem with handers which can't be used(both serverhandle and clienthandler) becouse the parameter 'e' is undefined or void: (Also a problem with MenuItemID)
I need to know which button is presed knowing 'e' and dont know whats wrong.
do get(){
var app = UiApp.createApplication()
var menu = menuBar();
var panel = app.createAbsolutePanel().setId("Panel");
var horizontalPanel = app.createHorizontalPanel().setId("horizontalPanel");
var verticalPanelDoc = app.createVerticalPanel().setId("verticalPanelDoc");
var verticalPanelMenu = app.createVerticalPanel().setId("verticalPanelMenu");
var scrollPanelDoc = app.createScrollPanel().setId("scrollPanelDoc").setSize('1000', '600');
verticalPanelMenu.add(menu);
verticalPanelDoc.add(scrollPanelDoc);
horizontalPanel.add(verticalPanelMenu);
horizontalPanel.add(verticalPanelDoc);
panel.add(horizontalPanel)
app.add(panel);
return app;
}
function show(e){
var ss =SpreadsheetApp.openById(TABLA_MENU);
//**testing 'e' = undefined or void**
var e_source = e.parameter.source;
ss.getSheetByName("menu").getRange("B"+6).setValue(e_source);
ss.getSheetByName("menu").getRange("C"+6).setValue(e);
//**result in cells : e_source = undefined e = {parameter={}}**
var app = UiApp.getActiveApplication();
var panel = app.getElementById("Panel");
var verticalPanelDoc = app.getElementById("verticalPanelDoc");
var horizontalPanel = app.getElementById("horizontalPanel");
var scrollPanelDoc = app.getElementById("scrollPanelDoc");
verticalPanelDoc.clear();
verticalPanelDoc.remove(scrollPanelDoc);
//**this will depend of 'e' **
var panelToShow = app.createCaptionPanel().setTitle("Show").setText("Show");
//
var label = app.createLabel().setText("Works!");
panelToShow.add(label);
verticalPanelDoc.add(panelToShow);
return app;
};
function menuBar(){
var ss = SpreadsheetApp.openById(TABLA_MENU);
var app = UiApp.getActiveApplication();
var absolutePanel = app.getElementById("absolutePanel");
var verticalPanelMenu = app.getElementById("verticalPanelMenu");
var horizontalPanel = app.getElementById("horizontalPanel");
var option_menu = app.getElementById("option_menu");
var arrayMenu = ss.getSheetByName("menu").getDataRange().getValues();
var arraySubMenu =ss.getSheetByName("submenu").getDataRange().getValues();
var arrayEnlacesSubMenu =ss.getSheetByName("enlaces").getDataRange().getValues();
var test1 = arraySubMenu[1][1];//A1
var test2 = arrayMenu[1];//A
var test3 = arrayEnlacesSubMenu[1][1]
// **create menu**
var menuBar = app.createMenuBar(true).setAnimationEnabled(true);
var handler = app.createServerHandler("show")
.addCallbackElement(verticalPanelMenu)
.addCallbackElement(horizontalPanel)
.addCallbackElement(absolutePanel);
// **add structure to menu**
for(var k=1; k<arrayMenu.length; k++) {
menuBar.addItem(arrayMenu[k][1], arrayMenu[k][1] = app.createMenuBar(true).setWidth("100%")).setWidth("100%");
for(var j=1; j<arraySubMenu[k].length; j++){
if(arraySubMenu[k][j]!=''){
var enlace = arrayEnlacesSubMenu[j][1].toString();
var a = arrayMenu[k][1];
var b = arraySubMenu[k][j];
//var c = this[arrayMenu[k][1]].addItem(arraySubMenu[k][j],handler).addSeparator(app.createMenuItemSeparator())
arrayMenu[k][1].addItem(arraySubMenu[k][j],handler).setId("1"+arraySubMenu[k][j])).addSeparator(app.createMenuItemSeparator());
//**THIS ID nither set the ID* show in navigator ID = ... class="gwt-MenuItem" id="gwt-uid-18" role="menuitem" aria-hasp....pan="1">Publicaciones 2012</td>
}
}
menuBar.addSeparator(app.createMenuItemSeparator());
}
return menuBar;
};
menuSpreadsheet
submenuSpreadsheet
Sorry, you can't have it (yet): http://code.google.com/p/google-apps-script-issues/issues/detail?id=317