Replacing placeholder values within a string - javascript

Not sure why my code is not working because the code I took from below is working in JSFiddle here
String.prototype.interpolate = (function() {
var re = /\[(.+?)\]/g;
return function(o) {
return this.replace(re, function(_, k) {
return o[k];
});
}
}());
var _obj = {
hey: 'Hey',
what: 'world',
when: 'today'
}
document.write(
'[hey]-hey, I saved the [what] [when]!'.interpolate(_obj)
);
But my code below doesn't seem to be doing the same thing. It still has the bracket values [NAME][ADDRESS][PHONE] and not the replaced data values:
$(document).ready(function () {
$('#goSearching').click(function () {
var isNumber = $.isNumeric($('#searchBox').val());
var theSearch = $('#searchBox').val();
var theURL = '';
if (isNumber) {
if (theSearch.length >= 10) {
//Search by NPI#
$('#titleOfSearchResult').html('P search results by NPI #:');
theURL = 'http://zzzzz.com:151/P/GetNPI/';
} else {
//Search by P #
$('#titleOfSearchResult').html('P search results by P #:');
theURL = 'http://zzzzzz.com:151/P/GetNo/';
}
} else {
//Search by P Name
$('#titleOfSearchResult').html('P search results by P Name:');
theURL = 'http://zzzzz.com:151/P/PName/';
}
$.ajax({
url : theURL + $('#searchBox').val() + '/',
type : 'GET',
dataType : 'xml',
timeout : 10000,
cache : false,
crossDomain : true,
success : function (xmlResults) {
console.log(xmlResults);
var _htmlObj = {};
$(xmlResults).find("P").each(function() {
_htmlObj = {
NAME : $(this).find("pName").text(),
ADDRESS : $(this).find("pSpecialty").text(),
PHONE : $(this).find("pUserid").text()
}
console.log($(this).find("pName").text());
console.log($(this).find("pSpecialty").text());
console.log($(this).find("pUserid").text());
$("#theResults").append(
'<p><strong>[NAME]</strong></p>' +
'<p>[ADDRESS]</p>' +
'<p>[PHONE]</p>' +
'<p> </p>'.interpolate(_htmlObj)
);
});
},
error : function(jqXHR, textStatus) {
console.log("error: " + textStatus);
}
});
});
String.prototype.interpolate = (function () {
var re = /\[(.+?)\]/g;
return function (o) {
return this.replace(re, function (_, k) {
return o[k];
});
}
}());
});
In the console it outputs the correct returned values but it won't replace those values with the placeholders [NAME][ADDRESS][PHONE].
Any help to fix this issue would be great! Thanks!

You're only calling interpolate on the last string
'<p><strong>[NAME]</strong></p>' +
'<p>[ADDRESS]</p>' +
'<p>[PHONE]</p>' +
'<p> </p>'.interpolate(_htmlObj)
Member access has a higher precedence than addition, so it needs to be:
('<p><strong>[NAME]</strong></p>' +
'<p>[ADDRESS]</p>' +
'<p>[PHONE]</p>' +
'<p> </p>').interpolate(_htmlObj)
Example from #TrueBlueAussie: jsfiddle.net/TrueBlueAussie/fFSYA/9

Related

Make a change to Javascript code that renumbers a list

I am unfamiliar with Javascript, but I would like to make a change to the following code. Currently, it renames macros in the program Keyboard Maestro in the format of 01), 02), etc. I would like it to simply use the format of a number followed by a space instead (i.e. 1 , 2 , etc.) I hope what I described makes sense. Thanks!
Part 1:
(function(inDesignMode) {
'use strict';
function dump(obj, desc) {
console.log((desc ? desc + ": " : "") + JSON.stringify(obj, null, "\t"));
}
var KMEditor = (function() {
var _editorAppName = "Keyboard Maestro";
var _editorApp;
return {
getEditorApp: function() {
return _editorApp ? _editorApp : _editorApp = Application(_editorAppName);
},
getEditorAppName: function() {return _editorAppName;},
getSelectedMacrosOrGroups: function() {
return this.getEditorApp().selectedmacros();
}
};
})();
var KMEngine = (function() {
var _engineApp;
return {
getAllMacrosSourceFileName: function() {
return this.getAppSupportFolderName() + "Keyboard Maestro Macros.plist";
},
getAppSupportFolderName: function() {
var app = Application.currentApplication();
app.includeStandardAdditions = true;
return app.pathTo('application support', { from: 'user domain' }) +
"/Keyboard Maestro/";
},
getEngineAppName: function() {
return "Keyboard Maestro Engine";
},
getEngineApp: function() {
if (!_engineApp)
_engineApp = Application(this.getEngineAppName());
return _engineApp;
},
readPlistBinaryFile: function(path) {
var data = $.NSData.dataWithContentsOfFile(path);
return ObjC.deepUnwrap(
$.NSPropertyListSerialization.propertyListWithDataOptionsFormatError(
data, $.NSPropertyListBinaryFormat_v1_0, 0, null));
},
};
})();
function getMacrosInfo(selectedMacroUUIDs) {
function getMacroName(macro) {
if (macro.Name)
return macro.Name;
throw Error("Un-named Macro UUID: " + macro.UID);
}
function getMacroInfo(macro) {
var info = {
macroUUID: macro.UID,
macroName: getMacroName(macro)
};
var matches = info.macroName.match(/^(\d\d)?(\))?(.*)/);
if (!matches || matches.length != 4)
throw Error("Could not parse macro name '" + info.macroName + "'");
info.prefixNumber = matches[1] || "";
info.macroNameNoPrefix = matches[3].trim();
return info;
}
function reOrderResult(macrosInfo, selectedMacroUUIDs) {
macrosInfo.macros = selectedMacroUUIDs.map(function(selectedMacroUUID) {
var info = macrosInfo.macros.find(function(macroInfo) {
return macroInfo.macroUUID === selectedMacroUUID;
});
if (!info)
throw Error("Could not find macro information for UUID '" + selectedMacroUUID + "'");
return info;
});
}
// getMacrosInfo()
var result = {
macros: []
};
var macroGroup;
var plist = KMEngine.readPlistBinaryFile(KMEngine.getAllMacrosSourceFileName());
plist.MacroGroups.forEach(function(group) {
if (group.Macros) {
group.Macros.forEach(function(macro) {
if (selectedMacroUUIDs.indexOf(macro.UID) >= 0) {
if (!result.groupUUID) {
macroGroup = group;
result.groupUUID = group.UID;
result.groupName = group.Name;
result.groupToggleMacroUID = group.ToggleMacroUID;
} else if (result.groupUUID !== group.UID) {
throw Error("Selected macros must all be from the same group");
}
result.macros.push(getMacroInfo(macro));
}
});
}
});
reOrderResult(result, selectedMacroUUIDs);
return result;
} // getMacrosInfo()
function execute() {
var selectedMacroUUIDs = KMEditor.getSelectedMacrosOrGroups();
if (!selectedMacroUUIDs || selectedMacroUUIDs.length < 2)
throw Error("You must select two or more macros");
var result = getMacrosInfo(selectedMacroUUIDs);
return JSON.stringify(result);
}
if (inDesignMode) {
return execute();
} else {
try {
return execute();
} catch (e) {
return "Error: " + e.message;
}
}
})(false);
Part 2:
(function(inDesignMode, designModeParams) {
'use strict';
var _kme = Application("Keyboard Maestro Engine");
function getKMVariable(name, required) {
var result = undefined;
if (inDesignMode && designModeParams)
result = designModeParams[name];
if (result === undefined)
result = _kme.getvariable(name);
if (required && !result)
throw Error("Variable '" + name + "' is empty");
return result;
}
var _km = Application("Keyboard Maestro");
function execute() {
var macroId = getKMVariable("palorg_MacroUUID", true);
var newName = getKMVariable("palorg_NewMacroName", true);
var macros = _km.macros.whose({id: {"=": macroId}});
if (macros.length == 0)
throw new Error("Macro '" + macroId + "' not found");
var macro = macros[0];
macro.name = newName;
return "OK";
}
if (inDesignMode) {
try {
return execute();
} catch (e) {
return "Error on line: " + e.line + ": " + e.message;
} finally {
try {
Application("Atom").activate();
} catch (e) {
}
}
} else {
try {
return execute();
} catch (e) {
return "Error: " + e.message;
}
}
})(false);
As per clarifications obtained in your comment, this is what you need:
01)macro --> 1 macro
To get that, you can try adding the following lines in execute() function in Part 2:
const regExp = /^0(.)\)/i; //Creates the regular expression
newName.replace(regex, '$1 '); //Replaces the match from the regex with a substring
macro.name = newName;
This is a regular expression substring replacement (more details here). Here's the breakdown on what's being done.
The ^ symbol denotes that a substring is being searched from the beginning of the string.
The next 0 is just a literal search for a 0 at the beginning of the string.
The next ( starts a parenthesized submatch string whose utility will be explained later.
The . indicates any single character.
The next ) end the parenthesized submatch string started earlier.
The next \) is for searching a ) literally which needs to be escaped with \ since ) has a special meaning of ending a parenthesized submatch string as mentioned above.
Now, the parenthesized submatch string is used so that after matching against the regular expression, the result can be used further to replace the matched string with. In this case,
01)macro will match 1 as the parenthesized submatch string since that's a single character after the leading 0 and before the ). This is used as $1 in the replace function so that after matching 01), it's replaced with 1 (notice the extra space, as is required by the question).

jQuery widget method not being detected

For the life of me I cannot see the suttle difference between copied code. The _getMiscData method in a child widget apparently doesn't exist according to the parent widget. Can someone explain this?
I tried different method names in case I was using a reserved word. I tried private and public method with same result.
$(function() {
$.widget("custom.textquestion", $.custom.base, {
_create: function() {
this.element.data("_getControlValue", this.getControlValue());
},
getControlValue: function() {
this.element.attr("usersanswer", this.getResponseJSON());
},
_getAnswerSelection: function(answer) {
var qname = this._getQuestionName();
var type = this.getType();
return '<div class="radio span6"><label><input type="text" class="answerfield" name="optradio-' + qname + '" value="' + answer.answertext + '"></label></div>'
},
_getAnswersDiv: function(answers) {
// DIV is required for wrapping around list of answers
// so that they can be added all at once.
var answerdivs = '<div class="answerlist">'
for (k = 0; k < answers.length; k++) {
answerdivs += this._getAnswerSelection(answers[k]);
}
answerdivs += '</div>';
return answerdivs;
},
_getPopulatedEditor: function(answers) {
var editanswerdiv = "";
for (p = 0; p < answers.length; p++) {
editanswerdiv += '<label>Default</label><input type="text" onblur="savequestiondata()" identifier="' + answers[p].answerid + '" name="editanswer' + this._getQuestionName(this.options.questioncontrol) + '" size="20" value="' + answers[p].answertext + '"/><br/>'
}
return editanswerdiv;
},
_getAnswersJSON: function(div) {
var answers = [];
$(div).find("input[name='editanswer" + this._getQuestionName(this.options.questioncontrol) + "']").each(function(i, u) {
var answer = {
answerid: $(this).attr('identifier'),
answertext: $(this).val(),
answerorder: 0,
rating: 0
};
answers.push(answer);
});
return answers;
},
_setAnswerJSON: function(answer) {
answer = answer.replace(/['"]+/g, '');
this.options.questioncontrol.find("input[name='optradio-" + this._getQuestionName() + "']").val(answer);
return true;
},
getResponseJSON: function() {
qname = this._getQuestionName();
console.log("The control name is " + qname);
var answer = this.options.questioncontrol.find("input[name='optradio-" + qname + "']").val();
console.log("The answer is " + answer);
return answer;
},
_refresh: function() {
qname = this._getQuestionName(this.options.questioncontrol);
// Create the divs for the answer block, then
// append to this question as the list of answers.
var answers = this._getStoredData().data.answers;
var answerhtml = this._getAnswersDiv(answers);
this.options.questioncontrol.find(".answer-list").html("");
this.options.questioncontrol.find(".answer-list").append(answerhtml);
// Get the explanation text and add to control.
var explanation = this._getStoredData().data.explanation;
this.options.questioncontrol.find(".explanation").text(explanation);
// Populate the editor controls with the answers that
// are already stored - ready for editing.
var editanswerhtml = this._getPopulatedEditor(answers);
this.options.questioncontrol.find(".editanswers").html("");
this.options.questioncontrol.find(".editanswers").append(editanswerhtml);
this.options.questioncontrol.find(".notes").text(explanation);
},
_getQuestionText: function(div) {
var qtext;
$(div).find("input[name='questiontextedit']").each(function() {
qtext = $(this).val();
});
return qtext;
},
_getMiscData: function() {
var info = [this.options.questioncontrol.find(".email-mask").val()];
return info;
},
_setOtherData: function(info) {
if (info.emailmask == "true")
this.options.questioncontrol.find(".email-mask").attr("checked", "checked");
else
this.options.questioncontrol.find(".email-mask").attr("checked", "");
},
_getExplanationText: function(div) {
var etext = $(div).find(".notes").val();
return etext;
}
});
});
$(function() {
$.widget("custom.base", {
// default options
options: {
questioncontrol: this,
questiondata: null,
_storedData: [],
},
_create: function() {
},
_refresh: function() {
},
getEditedAnswers: function(div) {
// Get the set of answers that were edited.
if (!div)
div = this.options.questioncontrol;
var answersresult = this._getAnswersJSON(div);
var question = this._getQuestionText(div);
var typename = this.getType();
var qname = this._getQuestionName(this.options.questioncontrol);
var pagenumber = this._getStoredData(qname).data.pagenumber;
var order = this._getStoredData(qname).data.order;
var explanation = this._getExplanationText(div);
var otherdata = this._getMiscData();
var result = {
title: question,
type: typename,
pageid: pagenumber,
qname: qname,
answers: answersresult,
questionorder: order,
explanation: explanation,
otherdata: otherdata
};
return result;
},
getType: function() {
return $(this.options.questioncontrol).attr('id');
},
setData: function(questiondata) {
// Set the title for the question. I.e, the text
// for the question.
this.options.questioncontrol.find(".questiontitle").text(questiondata.title);
this.options.questioncontrol.find("input[name='questiontextedit']").val(questiondata.title);
this.options.questioncontrol.find(".notes").text(questiondata.explanation);
// Store the data into datastore.
var stored = 0;
if (this._getStoredData(questiondata.qname) == null) {
this.options._storedData.push({
qname: questiondata.qname,
data: questiondata
});
} else {
var datastored = this._getStoredData(questiondata.qname);
datastored.data = questiondata;
}
if (questiondata.otherdata)
this._setOtherData(questiondata.otherdata);
this._refresh();
},
setAnswer: function(answer) {
this._setAnswerJSON(answer);
},
_getQuestionName: function() {
return this.options.questioncontrol.find('.questionname').val();
},
_getStoredData: function() {
var qname = this._getQuestionName(this.options.questioncontrol);
for (p = 0; p < this.options._storedData.length; p++) {
if (this.options._storedData[p].qname == qname)
return this.options._storedData[p];
}
return null;
},
});
});
The custom.base widget shouldn't return with "this.getMiscData is not a function"

How to access object array using javascript

console.log (dict) will give you
{"click here:":{"message":"点击这里"},"apply":{"message":"应用"},"a translation test!":{"message":"js翻译示例!"},"tabLanding":"欢迎","tabSetup":{"message":"安装"}}
I want tabSetup appear like 安装 in html
here is the html code:
<li class="tab_setup"></li>
what i see is it does not shows correctly just showed as [object Object]
it should showed as 安装
here is my java-script. Thanks
var dict = {};
var systemLang = navigator.language.toLowerCase().slice(0,2);
$(function () {
registerWords();
switch(getCookieVal("lang")) {
case "en" :
setLanguage("en");
break
case "zh" :
setLanguage("zh");
break
default:
setLanguage(systemLang);
}
console.log (dict);
console.log(JSON.stringify(dict));
// 切换语言事件
$("#enBtn").bind("click", function () {
setLanguage("en");
});
$("#zhBtn").bind("click", function () {
setLanguage("zh");
});
// $("#applyBtn").bind("click", function () {
// alert(__tr("a translation test!"));
// });
});
function setLanguage(lang) {
setCookie("lang=" + lang + "; path=/;");
translate(lang);
}
function getCookieVal(name) {
var items = document.cookie.split(";");
for (var i in items) {
var cookie = $.trim(items[i]);
var eqIdx = cookie.indexOf("=");
var key = cookie.substring(0, eqIdx);
if (name == $.trim(key)) {
return $.trim(cookie.substring(eqIdx + 1));
}
}
return null;
}
function setCookie(cookie) {
var Days = 30; //此 cookie 将被保存 30 天
var exp = new Date(); //new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = cookie+ ";expires=" + exp.toGMTString();
}
function translate(lang) {
if(sessionStorage.getItem(lang + "Data") != null){
dict = JSON.parse(sessionStorage.getItem(lang + "Data"));
}else{
loadDict();
}
$("[i18n]").each(function () {
switch (this.tagName.toLowerCase()) {
case "input":
$(this).val(__tr($(this).attr("i18n")));
break;
default:
$(this).text(__tr($(this).attr("i18n")));
}
});
}
function __tr(src) {
return (dict[src] || src);
}
function loadDict() {
var lang = (getCookieVal("lang") || "en");
$.ajax({
async: false,
type: "GET",
url: "/lang/"+lang + ".json",
success: function (msg) {
dict = msg;
sessionStorage.setItem(lang + 'Data', JSON.stringify(dict));
}
});
}
// 遍历所有lang属性的标签赋值
function registerWords() {
$('[i18n]:not(.i18n-replaced').each(function() {
var element = $(this);
element.html(translate(element.attr('i18n')));
element.addClass('i18n-replaced');
});
}
It works if json file like "tabSetup": "Set up". .It does not works if json file like "tabSetup": { "message": "Set up" }
function __tr has error, repair like this
function __tr(src) {
return (dict[src].message || src);
}

How to count duplicate array elements? (javascript)

I'm trying to make an XML based menu with JavaScript, XML and jQuery. I've been successful at getting the categories of the menu, but haven't been able to generate the items in the categories.
My script is as follows, and later in this thread, I've asked for suggestions for this code:
var animalsXMLurl = 'http://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml';
$(function() {
$.ajax({
url: animalsXMLurl, // name of file you want to parse
dataType: "xml",
success: function parse(xmlResponse) {
var data = $("item", xmlResponse).map(function() {
return {
id: $("animal_id", this).text(),
title: $("animal_title", this).text(),
url: $("animal_url", this).text(),
category: $("animal_category", this).text().split('/'),
};
}).get();
var first_item = category_gen(data, 0);
$('ul.w-nav-list.level_2').append(first_item);
var categnumber = new Array();
for (i = 1; i <= data.length; i++) //for splitting id, and getting 0 for category_number (1 or 2 or 3...and so on)
{
categnumber[i] = data[i].id.split('_');
console.log(categnumber[i][0]);
for (j = 1; j <= data.length; j++) //appending via a function.
{
var data_text = category_or_animal(data, categnumber, j);
console.log(data_text);
$('ul.w-nav-list.level_2').append(data_text);
}
}
function category_or_animal(d, catg, k) {
var catg1 = new Array();
var catg2 = new Array();
var catg1 = d[k].id.split('_');
if (d[k - 1]) {
var catg2 = d[k - 1].id.split('_');
//if(d[k-1].id)
if (catg1[0] != catg2[0])
return category_gen(d, k);
} else
return '</ul>' + animal_gen(d, k);
}
function category_gen(d, z) {
var category_var = '<li class="w-nav-item level_2 has_sublevel"><a class="w-nav-anchor level_2" href="javascript:void(0);"><span class="w-nav-title">' + d[z].category + '</span><span class="w-nav-arrow"></span></a><ul class="w-nav-list level_3">';
return category_var;
}
function animal_gen(d, z) {
var animal_var = '<li class="w-nav-item level_3"><a class="w-nav-anchor level_3" href="animals/' + d[z].url + '"><span class="w-nav-title">' + d[z].title + '</span><span class="w-nav-arrow"></span></a></li>';
return animal_var;
}
}, error: function() {
console.log('Error: Animals info xml could not be loaded.');
}
});
});
Here's the JSFiddle link for the above code: http://jsfiddle.net/mohitk117/d7XmQ/4/
In the above code I need some alterations, with which I think the code might work, so I'm asking for suggestions:
Here's the function that's calling separate functions with arguments to generate the menu in above code:
function category_or_animal(d, catg, k) {
var catg1 = new Array();
var catg2 = new Array();
var catg1 = d[k].id.split('_');
if (d[k - 1]) {
var catg2 = d[k - 1].id.split('_');
//if(d[k-1].id)
if (catg1[0] != catg2[0])
return category_gen(d, k);
} else
return animal_gen(d, k) + '</ul>';
}
At the if(catg1[0] != catg2[0]) it checks if the split string 1_2 or 1_3 is equal to 1_1 or 1_2 respectively. By split, I mean the first element: 1 .... if you have a look at the xml: [ :: Animals XML :: ], you'll see that the animal_id is in the format of %category_number% _ %item_number% ... So I need to create the menu with CATEGORY > ITEM (item=animal name)
Now if I could return category_gen() + animal() with animal(){ in a for loop for all the matching category id numbers} then maybe this could be complete! But I don't of a count script for conditioning the for loop (i=0;i<=count();i++)...
Would anyone know of how to get this script functioning?
Hard to tell what the provided JSFiddle is trying to do.
This is my best stab at it. I used JQuery to parse the XML out into categories and generate lists of items.
http://jsfiddle.net/d7XmQ/8/
"use strict";
var animalsXMLurl = 'http://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml';
$(function () {
var $menu = $('#menu');
$.ajax({
url: animalsXMLurl, // name of file you want to parse
dataType: "xml",
success: handleResponse,
error: function () {
console.log('Error: Animals info xml could not be loaded.');
}
});
function handleResponse(xmlResponse) {
var $data = parseResponse(xmlResponse);
createMenu($data);
}
function parseResponse(xmlResponse) {
return $("item", xmlResponse).map(function () {
var $this = $(this);
return {
id: $this.find("animal_id").text(),
title: $this.find("animal_title").text(),
url: $this.find("animal_url").text(),
category: $this.find("animal_category").text()
};
});
}
function createMenu($data) {
var categories = {};
$data.each(function (i, dataItem) {
if (typeof categories[dataItem.category] === 'undefined') {
categories[dataItem.category] = [];
}
categories[dataItem.category].push(dataItem);
});
$.each(categories, function (category, categoryItems) {
var categoryItems = categories[category];
$menu.append($('<h2>').text(category));
$menu.append(createList(categoryItems));
});
}
function createList(categoryItems) {
var $list = $('<ul>');
$.each(categoryItems, function (i, dataItem) {
$list.append(createItem(dataItem));
});
return $list;
}
function createItem(dataItem) {
return $('<li>').text(dataItem.title);
}
});
You can solve this without using any for/while loop or forEach.
function myCounter(inputWords) {
return inputWords.reduce( (countWords, word) => {
countWords[word] = ++countWords[word] || 1;
return countWords;
}, {});
}
Hope it helps you!

Autocomplete with javascript, not passing the variables

I'm using this autocomplete code to be able to pull stock information:
var YAHOO = {};
YAHOO.util = {};
YAHOO.util.ScriptNodeDataSource = {};
var stockSymbol;
var compName;
YUI({
filter: "raw"
}).use("datasource", "autocomplete", "highlight", function (Y) {
var oDS, acNode = Y.one("#ac-input");
oDS = new Y.DataSource.Get({
source: "http://d.yimg.com/aq/autoc?query=",
generateRequestCallback: function (id) {
YAHOO.util.ScriptNodeDataSource.callbacks =
YUI.Env.DataSource.callbacks[id];
return "&callback=YAHOO.util.ScriptNodeDataSource.callbacks";
}
});
oDS.plug(Y.Plugin.DataSourceJSONSchema, {
schema: {
resultListLocator: "ResultSet.Result",
resultFields: ["symbol", "name", "exch", "type", "exchDisp"]
}
});
acNode.plug(Y.Plugin.AutoComplete, {
maxResults: 10,
resultTextLocator: "symbol",
resultFormatter: function (query, results) {
return Y.Array.map(results, function (result) {
var asset = result.raw,
text = asset.symbol +
" " + asset.name +
" (" + asset.type +
" - " + asset.exchDisp + ")";
return Y.Highlight.all(text, query);
});
},
requestTemplate: "{query}&region=US&lang=en-US",
source: oDS
});
acNode.ac.on("select", function (e) {
alert(e.result.raw.name);
stockSymbol = e.result.raw.symbol;
compName = e.result.raw.name;
alert("stockSymbol is "+stockSymbol);
alert("compName is "+compName);
});
});
I have a text field where the text is being entered, then I need to display a few pieces of information based on what was entered:
$(document).ready(function(e) {
//$(".selector").button({icons: {primary: "ui-icon-search"}});
//$(".home").button({icons: {primary: "ui-icon-home"}});
var q = window.location.href.split("?ac-input=");
alert("q is "+q)
if (q && q[1])
$("input").val(q[1]);
alert("what is this?" +q[1]);
runForm();
});
..........
function runForm(){
$("#stock_news").html("");
//var stockSymbol = e.result.raw.symbol;
alert('stockSymbol in runForm is ' +stockSymbol);
alert('compname is runForm is '+compName);
var newsStocks = "http://query.yahooapis.com/v1/public/yql?.......";
$.getJSON(newsStocks, function(data) {
var headlines = data.query.results.a;
newStr = "<h3>Current Headlines</h3>";
newStr += "<ol>";
for(var i=0; i<headlines.length; ++i){
var news = headlines[i];
newStr += "<li><a href='"+news.href+"'>"+news.content+"</a></li>";
}
newStr += "</ol>";
$("#stock_news").html(newStr);
});
htmlStr = '<img src="http://chart.finance.yahoo.com/z?s='+stockSymbol+'&t=5d&q=l&l=off&z=s&region=US&lang=en-EN"/>';
$("#stock_graph").html(htmlStr);
}
What is happening is, the stockSymbol and compName are correctly set from entering, but for some reason nothing renders on the page, as q is undefined....Any ideas on where I am messing up here?
Figured it out. I needed to call runForm inside the acNode.ac.on("select", function (e)

Categories

Resources