http://jsfiddle.net/84nv2dmL/
I'm trying to get these images of letters to display in order. I tried creating divs dynamically and filling them with the img, but that didn't work. How can I get these letters to display in order?
jsfiddle code:
function getQueryStringVar(name){
var qs = window.location.search.slice(1);
var props = qs.split("&");
for (var i=0 ; i < props.length;i++){
var pair = props[i].split("=");
if(pair[0] === name) {
return decodeURIComponent(pair[1]);
}
}
}
function getLetterImage(tag){
var flickerAPI = "https://www.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
return $.getJSON( flickerAPI, {
tags: tag,
tagmode: "all",
format: "json"
})
.then(function (flickrdata) {
//console.log(flickrdata);
var i = Math.floor(Math.random() * flickrdata.items.length);
var item = flickrdata.items[i];
var url = item.media.m;
return url;
});
}
$(document).ready(function() {
var name = getQueryStringVar("name") || "Derek";
var str = "letter,";
var searchtags = new Array()
for (var i = 0; i < name.length; i++) {
//console.log(str.concat(searchtags.charAt(i)));
searchtags[i] = str.concat(name.charAt(i));
}
for (var j = 0; j < name.length; j++){
var request = getLetterImage(searchtags[j]);
request.done(function(url) {
$("body").append("<img src="+ url + "></img>");
//var ele = document.createElement("div");
//ele.setAttribute("class", "img" + j--);
//document.body.appendChild(ele);
//$("<img src="+ url +"></img>").appendTo("img"+j);
});
}
//$("#img"+i).html("<img src="+ url + "></img>");
});
You basically need to keep track of the order that you are appending your images to the DOM, and make sure that they are in sync with the letters in the name. Created a fiddle with a fix. Comments are in line:
http://jsfiddle.net/84nv2dmL/2/
function getQueryStringVar(name) {
var qs = window.location.search.slice(1);
var props = qs.split("&");
for (var i = 0; i < props.length; i++) {
var pair = props[i].split("=");
if (pair[0] === name) {
return decodeURIComponent(pair[1]);
}
}
}
function getLetterImage(tag) {
var flickerAPI = "https://www.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
return $.getJSON(flickerAPI, {
tags: tag.char,
tagmode: "all",
format: "json"
})
.then(function(flickrdata) {
//console.log(flickrdata);
var i = Math.floor(Math.random() * flickrdata.items.length);
var item = flickrdata.items[i];
var url = item.media.m;
// return an object with url AND index
return {
ind: tag.ind,
img: url
};
});
}
$(document).ready(function() {
var name = getQueryStringVar("name") || "Derek";
var urls = new Array(name.length); // array or URLs, in correct order
var urlCounter = []; // keeps count or URLs received
var str = "letter,";
var searchtags = new Array();
for (var i = 0; i < name.length; i++) {
searchtags[i] = {
char: str.concat(name.charAt(i)),
ind: i
};
}
for (var j = 0; j < name.length; j++) {
var request = getLetterImage(searchtags[j]);
request.done(function(url) {
// when request is done, place image url in 'urls' array, in the correct order
urls[url.ind] = url.img;
// push object to the counter array, just to keep count
urlCounter.push(url);
// check if all image urls have been collected
checkComplete();
});
}
function checkComplete() {
// if the number of URLs received is equal
// to the number of characters in the name
// append the images from the ordered array
if (urlCounter.length == name.length) {
for (var k = 0; k < urls.length; k++) {
$("body").append("<img src=" + urls[k] + "></img>");
}
}
}
});
$("#div_id").append("<img src="+ url + "></img>");
Here div_id is the id you gave to the div.
Append adds img tag with source src to it.
Please give the html code too along with the script to help understand the problem better
Related
I'm brand new to JS and am trying to build a template function (assignment in a MOOC) that basically returns a function that returns the rendered template based on an input string and delimiter.
Anyway, this is the code that I have so far and I have no idea why it is breaking.. I've really tried everything that I can think of!
var template = function(stringToParse, options) {
// find out if custom delimiters are being used
if (typeof options != 'undefined') {
var openDelim = options.open;
var closeDelim = options.close;
} else {
var openDelim = '*(';
var closeDelim = ')*';
}
// get the length of the closing delim for parsing later
var delimCharLen = closeDelim.length;
// helper function
function parseOutFiller(_array) {
// get an array of the indices of each closing delim in the string
var closingDelims = [];
for (i=0; i < _array.length; i++) {
closingDelims.push(_array[i].indexOf(closeDelim));
}
// remove the filler text leading up to the closing dim in each substring
for (i = 0; i < _array.length; i++) {
if (closingDelims[i] > 0) {
_array[i] = _array[i].slice(closingDelims[i] + delimCharLen)
}
}
return _array
}
// split array, get the closing indices, and parse out the filler text
var splitArray = stringToParse.split(openDelim);
var parsedString = parseOutFiller(splitArray);
return new Function("var locParsedString = [" + parsedString + "];\
var inputCopy = [];\
for (i=0; i < arguments.length-1; i++) {\
inputCopy.push(arguments[i])\
}\
var templateString = '';\
for (i=0; i < inputCopy.length; i++) {\
templateString += locParsedString[i];\
templateString += inputCopy[i];\
}\
templateString += locParsedString[locParsedString.length-1];\
nRepeat = arguments[arguments.length-1];\
for (i=0; i < nRepeat; i++) {\
console.log(templateString);\
}"
)
}
Then when I run it...
var string = "Is <<! thing !>> healthy to <<! action !>>?";
var logResult = template(string, {open: '<<!', close: '!>>'});
logResult('this', 'eat', 3)
/*
Which should print:
"Is this healthy to eat?"
"Is this healthy to eat?"
"Is this healthy to eat?"
*/
Thanks in advance!
Instead of using new Function(), just use return function () { }.
That way, there is no need to create locParserString inside the function. You can use parsedString directly:
var template = function(stringToParse, options) {
// find out if custom delimiters are being used
if (typeof options != 'undefined') {
var openDelim = options.open;
var closeDelim = options.close;
} else {
var openDelim = '*(';
var closeDelim = ')*';
}
// get the length of the closing delim for parsing later
var delimCharLen = closeDelim.length;
// helper function
function parseOutFiller(_array) {
// get an array of the indices of each closing delim in the string
var closingDelims = [];
for (i=0; i < _array.length; i++) {
closingDelims.push(_array[i].indexOf(closeDelim));
}
// remove the filler text leading up to the closing dim in each substring
for (i = 0; i < _array.length; i++) {
if (closingDelims[i] > 0) {
_array[i] = _array[i].slice(closingDelims[i] + delimCharLen)
}
}
return _array
}
// split array, get the closing indices, and parse out the filler text
var splitArray = stringToParse.split(openDelim);
var parsedString = parseOutFiller(splitArray);
return function () {
var inputCopy = [];
for (i=0; i < arguments.length-1; i++) {
inputCopy.push(arguments[i])
}
var templateString = '';
for (i=0; i < inputCopy.length; i++) {
templateString += parsedString[i];
templateString += inputCopy[i];
}
templateString += parsedString[parsedString.length-1];
nRepeat = arguments[arguments.length-1];
for (i=0; i < nRepeat; i++) {
console.log(templateString);
}
};
}
I have a question. When querying my Json object, although i have my Field as same name and all Json rows available give me an error that is undefined.
//e.g: row.DepParentId
Bellow is my code. Am I missing some tag?
function convert(rows) {
debugger;
function exists(rows, parent) {
for (var i = 0; i < rows.length; i++) {
if (rows[i].DepId === parent) return true;
}
return false;
}
var nodes = [];
// get the top level nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (!exists(rows, row.DepParentId)) {
nodes.push({
id: row.DepId,
name: row.Title
});
}
}
var toDo = [];
for (var i = 0; i < nodes.length; i++) {
toDo.push(nodes[i]);
}
while (toDo.length) {
var node = toDo.shift();
// the parent node
// get the children nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.DepParentId == node.Id) {
var child = {
Id: row.DepId,
Name: row.Title
};
if (node.options) {
node.options.push(child);
} else {
node.options = [child];
}
toDo.push(child);
}
}
}
return nodes;
}
My Json example for one row picked from Firefox
"{"DepId":7,"DepParentId":3,"Title":"OTT"}"
Thanks for helping
Joao
thanks all for helping, it's working now, the problem was the JSON.stringify() was returning only an [Object] so when you use JSON.parse() generates a sintax error.
function onLoaded() {
var itemsCount = items.get_count();
for (var i = 0; i < itemsCount; i++) {
var item = items.itemAt(i);
var dep = JSON.stringify(item.get_fieldValues());
deps.push(dep);
}
So, i had to change the format to be valid to parse like this
var dt = "[" + deps + "]";
var ret = JSON.parse(dt);
Thanks
Joao
I need to sort list strings under the table ,so for that i have written following lines of code but on console i am not getting any values:
var j = 9;
var rows = element.all(by.repeater('row in renderedRows'));
var column = element.all(by.repeater('col in renderedColumns'));
expect(rows.count()).toEqual(5); //here its printing number of rows
expect(column.count()).toEqual(5); //here its printing number of columns
var arr = [rows.count()];
for (var i = 0; i < rows.count(); i++) {
console.log("aai" + i);
if (i = 0) {
//var columnvalue=column.get(9).getText();
var columnvalue = column.get(9).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the value first value of column
console.log("value1" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("aa" + ss.trim());
});
} else {
var j = j + 8;
var columnvalue = column.get(j).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the other values of column
console.log("value" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("ab" + ss.trim());
});
}
}
Sorting_Under_Table: function(col){
test = [];
var m;
var dm = 0;
element(by.xpath('//div[#class="ngHeaderScroller"]/div['+col+']')).click();
element.all(by.repeater('row in renderedRows')).then(function(row) {
m = row.length;
for (i = 1; i <= row.length; i++)
{
user_admin_table_name = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+i+']/div['+col+']'));
user_admin_table_name.getText().then(function(text) {
var test_var1 = text.toLowerCase().trim();
test.push(test_var1);
var k = test.length
if (k == m){
for (j = 0; j < test.length; j++){
test.sort();
d=j+1;
user_admin_table_name1 = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+d+']/div['+col+']'));
user_admin_table_name1.getText().then(function(text1) {
var test_var2 = text1.toLowerCase().trim();
if (test_var2 == test[dm]){
expect(test_var2).toEqual(test[dm]);
dm = dm +1;
}else {
expect(test_var2).toEqual(test[dm]);
log.error("Sorting is not successful");
dm = dm +1;
}
});
}
}
});
}
});
},
You can use this code for sorting and verifying is it sorted or not
I'm not sure how your above example is doing any sorting, but here's a general solution for trimming and then sorting:
var elementsWithTextToSort = element.all(by.xyz...);
elementsWithTextToSort.map(function(elem) {
return elem.getText().then(function(text) {
return text.trim();
});
}).then(function(trimmedTexts) {
return trimmedTexts.sort();
}).then(function(sortedTrimmedTexts) {
//do something with the sorted trimmed texts
});
I am trying to re-populate a form from some values in localStorage. I can't quite manage the last part to get the loop to populate my name and values.
function loadFromLocalStorage() {
PROCESS_SAVE = true;
var store = localStorage.getItem(STORE_KEY);
var jsn = JSON.parse(store);
console.log(jsn);
if(store.length === 0) {
return false;
}
var s = jsn.length-1;
console.log(s);
for (var i = 0; i < s.length; i++) {
var formInput = s[i];
console.log(s[i]);
$("form input[name='" + formInput.name +"']").val(formInput.value);
}
}
Could I get some pointers please.
Your issue is in this section of code.
var s = jsn.length-1;
console.log(s);
for (var i = 0; i < s.length; i++) {
You are setting s to the length of the jsn array minus 1, then using it as if it were jsn. I think you intended something like this.
function loadFromLocalStorage() {
PROCESS_SAVE = true;
var store = localStorage.getItem(STORE_KEY);
var jsn = JSON.parse(store);
console.log(jsn);
if(store.length === 0) {
return false;
}
for (var i = 0; i < jsn.length; i++) {
var formInput = jsn[i];
console.log(jsn[i]);
$("form input[name='" + formInput.name +"']").val(formInput.value);
}
}
Im currently working on this script that is written in javascript that returns data from the netsuite ERP platform.
Right now we have the code returning in an array, whilst this is good, it is a result of a dataset of product information.
The script is querying for 3 products, and as a result it returns an array of 21 keys.
this should be returning 3 arrays of arrays so we can handle the content easily externally to Netsuite.
I for the life of me cant figure out which loop I am required to create a new array to manage the content.
function loadRecord(request, response)
{
var recType = request.getParameter('recType');
var savedSearchId = request.getParameter('savedSearchId');
var internalid = request.getParameter('internalid');
//perform the required search.
var filter = [];
if(recType == 'customer' || recType == 'contact' )
{
filter[0] = new nlobjSearchFilter('internalid', null, 'is', internalid); // just get the 1 item by the internal id of the record
}
if( recType == 'item')
{
var internal_ids = new Array();
internal_ids[0] = 25880;
internal_ids[1] = 25980;
internal_ids[2] = 333 ;
filter[0] = new nlobjSearchFilter('internalid', null, 'anyOf', internal_ids); // just get the 1 item by the internal id of the record
}
if(recType == 'transaction')
{
filter[0] = new nlobjSearchFilter('type',null,'anyOf','SalesOrd');
filter[1] = new nlobjSearchFilter('internalid','customer','is', internalid );
}
var rsResults = nlapiSearchRecord(recType, savedSearchId, filter);
var rsObj = [];
// not sure how to make each row a new array of arrays so it is structured more elegantly...
for (x = 0; x < rsResults.length; x++)
{
var flds = rsResults[x].getAllColumns();
for (i = 0; i < flds.length; i++)
{
var rowObj = {};
rowObj.name = flds[i].getName();
rowObj.label = flds[i].getLabel();
rowObj.val = rsResults[x].getValue(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary());
rowObj.txtval = rsResults[x].getText(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary())
rsObj.push(rowObj);
}
}
response.write(JSON.stringify(rsObj));
}
Any help greatly appreciated
Is this what you're looking for?
var rsObj = [];
var rowArr, fields, x, i;
for (x = 0; x < rsResults.length; x++)
{
flds = rsResults[x].getAllColumns();
for (i = 0; i < flds.length; i++)
{
rowArr = rsObj[x] = [];
rowArr.push(flds[i].getName());
rowArr.push(flds[i].getLabel());
rowArr.push(rsResults[x].getValue(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary()));
rowArr.push(rsResults[x].getText(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary()));
}
}
console.log(rsObj[0][0]); // row0.name
console.log(rsObj[2][1]); // row2.label
Maybe something like this:
for (var x = 0; x < rsResults.length; x++)
{
var flds = rsResults[x].getAllColumns();
for (var i = 0; i < flds.length; i++)
{
rsObj.push({
name: flds[i].getName(),
label: flds[i].getLabel(),
val: rsResults[x].getValue(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary()),
txtval: rsResults[x].getText(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary())
});
}
}
If you are using ECMAScript5, you cold simplify the loop with forEach, like this:
rsResults.forEach(function(result) {
result.getAllColumns().forEach(function(fields) {
rsObj.push({
name: fields.getName(),
label: fields.getLabel(),
val: result.getValue(fields.getName(), fields.getJoin(), fields.getSummary()),
txtval: result.getText(fields.getName(), fields.getJoin(), fields.getSummary())
});
});
});
This must solve you problem. Some declaration problem might be there.
var rsObj = [];
for (int x = 0; x < rsResults.length; x++)
{
var flds = rsResults[x].getAllColumns();
for (int i = 0; i < flds.length; i++)
{
var rowObj = [];
rowObj.push(flds[i].getName());
rowObj.push(flds[i].getLabel());
rowObj.push(rsResults[x].getValue(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary()));
rowObj.push(rsResults[x].getText(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary()));
rsObj.push(rowObj);
}
}