I am getting 0 values for my array when I try to add DOM elements from a webpage, how to add values to lists in .each function? - append

On console it presents just empty array and 0's for all the elements on the Business Insider page with the specific selectors. How can I add each number (which is views on their site) as a list or string of numbers and then .length on the variable and push it to my html interface?
var request = require('request');
var cheerio = require('cheerio');
var bilist = new Array();
//var x = document.getElementById('bi-stats').innerHTML;
var url = 'http://www.businessinsider.com/moneygame';
request(url, function(err,resp,body)
{
if (err)
throw err;
$ = cheerio.load(body); //create the dom object string
$('span.hot').each(function() {
$(this).text().append(bilist);
console.log(bilist);
console.log(bilist.length);
});
});
function start() {
window.addEventListener('load', bi_list(), false);
}

So jQuery has a different syntax for the 'for' iterator.
The correct code is shown below which appends the text element that contains # of views of the site Business Insider.
$('span.hot').each(function(i, elem) {
bilist[i] = $(this).text();
});

Related

get value for specific question/item in a Google Form using Google App Script in an on submit event

I have figured out how to run a Google App Script project/function on a form submit using the information at https://developers.google.com/apps-script/guides/triggers/events#form-submit_4.
Once I have e I can call e.response to get a FormResponse object and then call getItemResponses() to get an array of all of the responses.
Without iterating through the array and checking each one, is there a way to find the ItemResponse for a specific question?
I see getResponseForItem(item) but it looks like I have to somehow create an Item first?
Can I some how use e.source to get the Form object and then find the Item by question, without iterating through all of them, so I could get the Item object I can use with getResponseForItem(item)?
This is the code I use to pull the current set of answers into a object, so the most current response for the question Your Name becomes form.yourName which I found to be the easiest way to find responses by question:
function objectifyForm() {
//Makes the form info into an object
var myform = FormApp.getActiveForm();
var formResponses = myform.getResponses()
var currentResponse = formResponses[formResponses.length-1];
var responseArray = currentResponse.getItemResponses()
var form = {};
form.user = currentResponse.getRespondentEmail(); //requires collect email addresses to be turned on or is undefined.
form.timestamp = currentResponse.getTimestamp();
form.formName = myform.getTitle();
for (var i = 0; i < responseArray.length; i++){
var response = responseArray[i].getResponse();
var item = responseArray[i].getItem().getTitle();
var item = camelize(item);
form[item] = response;
}
return form;
}
function camelize(str) {
str = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()#\+\?><\[\]\+]/g, '')
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index == 0 ? match.toLowerCase() : match.toUpperCase();
});
}
//Use with installable trigger
function onSubmittedForm() {
var form = objectifyForm();
Logger.log(form);
//Put Code here
}
A couple of important things.
If you change the question on the form, you will need to update your
code
Non required questions may or may not have answers, so check if answer exists before you use it
I only use installable triggers, so I know it works with those. Not sure about with simple triggers
You can see the form object by opening the logs, which is useful for finding the object names

Xamarin.Android How to Get Google Play Store app version number using Dcsoup Nuget Plugin?

I am trying to get the latest version number of my store app in order to notify user for updates if they are using an older version.
This is my code so far but its obviously just retrieving the div containing the text "Version Number". How do I get the actual version number (in this case 1.1) referring to the attached screenshot of the DOM tree?
public static string GetAndroidStoreAppVersion()
{
string androidStoreAppVersion = null;
try
{
using (var client = new HttpClient())
{
var doc = client.GetAsync("https://play.google.com/store/apps/details?id=" + AppInfo.PackageName + "&hl=en_CA").Result.Parse();
var versionElement = doc.Select("div:containsOwn(Current Version)");
androidStoreAppVersion = versionElement.Text;
}
}
catch (Exception ex)
{
// do something
Console.WriteLine(ex.Message);
}
return androidStoreAppVersion;
}
According to the parser doc,the containsOwm selector selects elements that directly contain the specified text.
As a result, your code
var versionElement = doc.Select("div:containsOwn(Current Version)");
will surely return "Current Version". The real element you would like to get is the child of the child of the sibling of "Current Version" element. So you would have to get that element using the selector.
So you can get the version number in this way:
var versionElement = doc.Select("div:containsOwn(Current Version)");
Element headElement = versionElement[0];
Elements siblingsOfHead = headElement.SiblingElements;
Element contentElement = siblingsOfHead.First;
Elements childrenOfContentElement = contentElement.Children;
Element childOfContentElement = childrenOfContentElement.First;
Elements childrenOfChildren = childOfContentElement.Children;
Element childOfChild = childrenOfChildren.First;
androidStoreAppVersion = childOfChild.Text;

jsTree customize <li> using the alternative JSON format along with AJAX

I am using the alternative JSON format along with AJAX to load data in tree. Now there is a new ask, I am required to add a new element at the end of <li> tag.
I have created sample URL to display what I am currently doing.
Tree crated using alternative JSON format along with AJAX
And how the new LI should appear
Tree created using hard coded HTML but shows how the LI should look like
I think I should be able to do this if I use HTML Data but since the project is already live with JSON format this would require me to change a lot so before I start making this major change I just wanted to check if this is possible using JSON and AJAX format or not.
So I got answer from Ivan - Answer
In short there is misc.js in the src folder which has question mark plugin, this is the best example of what I wanted to do.
I tweaked its code for my needs and here is the new code.
(function ($, undefined) {
"use strict";
var span = document.createElement('span');
span.className = 'glyphicons glyphicons-comments flip jstree-comment'
$.jstree.defaults.commenticon = $.noop;
$.jstree.plugins.commenticon = function (options, parent) {
this.bind = function () {
parent.bind.call(this);
};
this.teardown = function () {
if (this.settings.commenticon) {
this.element.find(".jstree-comment").remove();
}
parent.teardown.call(this);
};
this.redraw_node = function (obj, deep, callback, force_draw) {
var addCommentIcon = true;
var data = this.get_node(obj).data;
//....Code for deciding whether comment icon is needed or not based on "data"
var li = parent.redraw_node.call(this, obj, deep, callback, force_draw);
if (li && addCommentIcon) {
var tmp = span.cloneNode(true);
tmp.id = li.id + "_commenticon";
var $a = $("a", li);
$a.append(tmp);
}
return li;
};
};
})(jQuery);

dojo.data.ItemFileReadStore: Invalid item argument. while reloading data

I am facing a strange problem here. I have a Select box displaying Department field value. Onchange of the department option, I have to populate the grid. When the page loads first time, the onChange event works fine and the data gets loaded perfectly in the grid. When I change the Department in the Select box, I get error in firebug "dojo.data.ItemFileReadStore: Invalid item argument".
I checked the JSON returned from server and it is exactly same as the JSON loaded earlier. Here are the code snippet of my code
HTML
<div id="costCenter" data-dojo-type="dijit/form/Select" data-dojo-attach-point="costCenter" data-dojo-attach-event="onChange:loadStacks"></div>
JS
loadStacks: function() {
var requestParams = {};
requestParams.Action = "getStacks";
requestParams.callType = "ajaxCall";
requestParams.deptID = deptID;
var docData = null;
request.invokePluginService("MyPlugin", "UtilityService",
{
requestParams: requestParams,
requestCompleteCallback: lang.hitch(this, function(response) { // success
docData= response.Data;
var dataStore = new dojo.data.ItemFileReadStore({data: docData});
grid = dijit.byId("docGrid");
grid.attr('structure', docStructure);
grid.attr('store', dataStore);
grid.render();
})
}
);
}
JSON data returned:
docData : {"items":[{"docName":"test3","id":135,"order":1},{"docName":"Ashish","id":4085,"order":21},{"docName":"fsdfsadf","id":4088,"order":23}],"identifier":"docName"}
Any idea about it?
Solved it myself. Added below lines before setting new store to the grid.
if (null != grid.store)
{
grid.store.close();
grid.store.fetch({query: {docName: "*"}});
grid._refresh();
}
And set clearOnClose: true while setting new store.

using jQuery selector with a dom element

I have a javascript function that receives a dom element as a parameter. In this function I am trying to get to the closest ancestor 'form'. I wanted to use:
function submit_form(obj)
{
var form1 = $(obj).closest("form");
alert (form1.id);
}
here obj is a dom element of submit type. I just don't seem to get it working.
Could someone please help?
You want
function submit_form(obj)
{
var form1 = $(obj).closest("form")[0];
alert (form1.id);
}
The result of jQuery selection/traversal functions always is an array, possibly with one element only, but still an array. Index into the array to get actual DOM elements.
However, you can do this without jQuery as long as obj is an input/select/textarea element.
function submit_form(obj)
{
var form1 = obj.form;
alert (form1.id);
}
For the sake of completeness, you could also stay within jQuery and do
function submit_form(obj)
{
var $form1 = $(obj).closest("form");
alert ( $form1.attr("id") );
}
function closest(obj, tagName) {
// Go up in the tree until you find the ancestor form
while (obj.parent !== null) {
if (obj.nodeType === 1) {
parent = obj.parentNode;
if (parent.tagName === tagName) {
return parent;
}
}
}
// If no form exists return null
if (obj.tagName !== tagName) {
return null;
}
}
Use it in this way
var closestForm = closest(obj, 'FORM')
form1 would be a jQuery object, so you can either use .attr("id"), or access the DOM element itself using [0].id:
var form1 = $(obj).closest("form");
alert(form1.attr("id"));
var form2 = $(obj).closest("form")[0];
alert(form2.id);