Can I save multiple JavaScript Object methods as a variable? - javascript

I am writing an extension for a text-editor (Brackets) that can generate HTML and append libraries automatically in the HTML.
I have an Object called 'choice'.
This modal requests the users input:
choice grabs the user's input by defining methods on choice
partial JS here:
var choice = new Object();
choice.language = function () {
//Buid HTML top 'head'
var htmlTop = "<!DOCTYPE html>" + "<html>" + "<head lang='";
//Grab Selected Language Type
var languageChoice = document.getElementById("languages").value;
//Determine what Selected Language type is and complete HTML 'head'
if (languageChoice === "english") {
languageChoice = "en";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "german") {
languageChoice = "de";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "spanish") {
languageChoice = "es";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "french") {
languageChoice = "fr";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "italian") {
languageChoice = "it";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "chinese") {
languageChoice = "zh-cn";
return htmlTop + languageChoice + "'>";
}
}; //end choice.language
choice.charset = function () {
//Build meta and the rest of the 'head tag'
var htmlCharset_Beginning = "<meta charset='";
var htmlCharset_End = "'>" + "<title> -Insert Title- </title>" + "<!-- Insert CSS links below -->" + "</head>" + "<body>";
var charsetChoice = document.getElementById("charset").value;
if (charsetChoice === "utf8") {
charsetChoice = "UTF-8";
return htmlCharset_Beginning + charsetChoice + htmlCharset_End;
} else {
charsetChoice = "UTF-16";
return htmlCharset_Beginning + charsetChoice + htmlCharset_End;
}
}; // end choice.charset
choice.doctype = function () {
var doctypeChoice = document.getElementById("doctype").value;
return doctypeChoice;
}; // end doctype
choice.libraries = function () {
var checkedBoxes = getCheckedBoxes("lib_checkboxes");
checkedBoxes.forEach(function(item){
var scripts =+ $(item).data('script');
});//End forEach
var bottomHTML = scripts + "</body>" + "</html>";
return bottomHTML;
}; //End choice.libraries
var chosenTemplate = function(){
var template = choice.language() + choice.charset() + choice.libraries();
// insert html into file, this will overwrite whatever content happens to be there already
EditorManager.getCurrentFullEditor()._codeMirror.setValue(template);
// automatically close the modal window
$('#templates_modalBtn').click();
};
//Get checkedBoxes function
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i = 0; i < checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
} // End action();
//JEFF STOP CODING HERE
// Register the commands and insert in the File menu
CommandManager.register(Strings.MENU_COMMAND, 'templates', action);
var menu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
menu.addMenuDivider();
menu.addMenuItem('templates');
}); //end define;
QUESTION:
Can I save multiple methods (each method returns a string) as a variable?
Example here:
var chosenTemplate = function(){
var template = choice.language() + choice.charset() + choice.libraries();
// insert html into file, this will overwrite whatever content happens to be there already
EditorManager.getCurrentFullEditor()._codeMirror.setValue(template);
// automatically close the modal window
$('#templates_modalBtn').click();
};
My code is loading with no errors, but its not executing at all so I am trying to debug and figure out what is going wrong...

Before you realize the function 'chosenTemplate', you should check whether the document stream of the page has already downloaded. If it not, you may not be able to get the value of the widget (empty).

Related

How to populate HTML drop down with Text File using JavaScript?

I have been stuck on this problem for a while now, Basically i want to populate the below select with option group and option check boxes. The text file imports to JS just fine, i'm getting the problem trying to populate the drop down. Here is my HTML:
function LoadTxtFile(p) {
var AllTxtdata = '';
var targetFile = p.target.files[0];
if (targetFile) {
// Create file reader
var FileRead = new FileReader();
FileRead.onload = function (e) {
if (FileRead.readyState === 2) {
AllTxtdata = FileRead;
// Split the results into individual lines
var lines = FileRead.result.split('\n').map(function (line) {
return line.trim();
});
var select = $("#MySelect");
var optionCounter = 0;
var currentGroup = "";
lines.forEach(function (line) {
// If line ends it " -" create option group
if (line.endsWith(" -")) {
currentGroup = line.substring(0, line.length - 2);
optionCounter = 0;
select.append("<optgroup id'" + currentGroup + "' label='" + currentGroup + "'>");
// Else if the line is empty close the option group
} else if (line === "") {
select.append("</optgroup>");
// Else add each of the values to the option group
} else {
select.append("<option type='checkbox' id='" + (currentGroup + optionCounter) + "' name'"
+ (currentGroup + optionCounter) + "' value='"
+ line + "'>" + line + "</option>");
}
});
}
}
FileRead.readAsText(targetFile);
}
}
document.getElementById('file').addEventListener('change', LoadTxtFile, false);
<html>
<body>
<select name="MySelect" id="MySelect"/>
</body>
</html>
I believe you are using append incorrectly as you are dealing with partial nodes with the optgroup. I would build the html snippet then append it in one go. This would also bring a performance benefit as multiple DOM manipulations can get expensive.
I'd do something like the following.
function LoadTxtFile(p) {
var AllTxtdata = '';
var htmlString = '';
//Optional Templates. I find them more readable
var optGroupTemplate = "<optgroup id='{{currentGroup}}' label='{{currentGroup}}'>";
var optionTemplate = "<option type='checkbox' id='{{currentGroupCounter}}' name='{{currentGroupCounter}}' value='{{line}}'>{{line}}</option>";
var targetFile = p.target.files[0];
if (targetFile) {
// Create file reader
var FileRead = new FileReader();
FileRead.onload = function (e) {
if (FileRead.readyState === 2) {
AllTxtdata = FileRead;
// Split the results into individual lines
var lines = FileRead.result.split('\n').map(function (line) {
return line.trim();
});
var select = $("#MySelect");
var optionCounter = 0;
var currentGroup = "";
lines.forEach(function (line) {
// If line ends it " -" create option group
if (line.endsWith(" -")) {
currentGroup = line.substring(0, line.length - 2);
optionCounter = 0;
htmlString += optGroupTemplate.replace("{{currentGroup}}", currentGroup);
// Else if the line is empty close the option group
} else if (line === "") {
htmlString +="</optgroup>";
// Else add each of the values to the option group
} else {
//I'm assuming you want to increment optionCounter
htmlString += optionTemplate.replace("{{currentGroupCounter}}", currentGroup + optionCounter).replace("{{line}}", line);
}
});
select.append(htmlString);
}
}
FileRead.readAsText(targetFile);
}
}
document.getElementById('file').addEventListener('change', LoadTxtFile, false);
NOTE the above is untested and may need some debugging.

How to use Angular.js to populate multiple select fields using AJAX calls to different endpoints

I apologize up front for the possible lack of clarity for this question, but I'm new to Angular.js and my knowledge of it is still slightly hazy. I have done the Angular.js tutorial and googled for answers, but I haven't found any.
I have multiple select/option html elements, not inside a form element, and I'm populating them using AJAX. Each form field is populated by values from a different SharePoint list. I'm wondering if there is a way to implement this using Angular.js?
I would like to consider building this using Angular because I like some of it features such as data-binding, routing, and organizing code by components. But I can't quite grasp how I could implement it in this situation while coding using the DRY principle.
Currently, I have a single AJAX.js file and I have a Javascript file that contains an array of the different endpoints I need to connect to along with specific query parameters. When my page loads, I loop through the arrays and for each element, I call the GET method and pass it the end-point details.
The code then goes on to find the corresponding select element on the page and appends the option element returned by the ajax call.
I'm new to Angular, but from what I understand, I could create a custom component for each select element. I would place the component on the page and all the select and options that are associated with that component would appear there. The examples I've seen demonstrated, associate the ajax call with the code for the component. I'm thinking that I could use a service and have each component dependent on that service and the component would pass it's specific query details to the service's ajax call.
My current code - Program flow: main -> data retrieval -> object creation | main -> form build.
Called from index.html - creates the multiple query strings that are passed to ajax calls - ajax calls are once for each query string - the very last function in the file is a call to another function to build the form elements.
var snbApp = window.snbApp || {};
snbApp.main = (function () {
var main = {};
main.loadCount = 0;
main.init = function () {
function buildSelectOptions(){
//***
//Build select options from multiple SharePoint lists
//***
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
for(var i = 0; i < listsArray.length; i++){
var listItem = listsArray[i];
var qryStrng = listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
var listDetails = {
listName: listItem.list,
listObj: listItem,
url: "http://myEnv/_vti_bin/listdata.svc/" + listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
};
var clientContext = new SP.ClientContext.get_current();
clientContext.executeQueryAsync(snbApp.dataretriever.letsBuild(listDetails), _onQueryFailed);
}
//***
//Build select option from other API endpoint
//***
var listDetails = {
listName:"SNB_SecondaryActivityCodes",
url: "http://myEnv/requests/odata/v1/Sites?$filter=(IsMajor eq true or IsMinor eq true) and IsActive eq true and IsPending eq false and CodePc ne null and IsSpecialPurpose eq false&$orderby=CodePc"
};
snbApp.dataretriever.letsBuild(listDetails);
}
buildSelectOptions();
//***
//Add delay to populate fields to ensure all data retrieved from AJAX calls
//***
var myObj = setTimeout(delayFieldPopulate,5000);
function delayFieldPopulate(){
var optObj = snbApp.optionsobj.getAllOptions();
var osType = $("input[name=os_platform]:checked").val();
snbApp.formmanager.buildForm(osType, optObj);
}
};
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return main
})();
AJAX calls here - called from main/previous file:
var snbApp = window.snbApp || {};
snbApp.dataretriever = (function () {
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
function getListData(listItem) {
var eventType = event.type;
var baseURL = listItem.url;
$.ajax({
url: baseURL,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
})
.done(function(results){
snbApp.objectbuilderutility.buildObjectFields(results, listItem);
})
.fail(function(xhr, status, errorThrown){
//console.log("Error:" + errorThrown + ": " + myListName);
});
}
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return{
letsBuild:function(item) {
getListData(item);
}
};
})();
Builds a item name object - called from recursive AJAX calls / previous file
var snbApp = window.snbApp || {};
snbApp.objectbuilderutility = (function () {
function formatItemCode(itemCode, eventType){
if(eventType !== 'change'){ //for load event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(0,3);
}
}else{ //for change event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(3);
}
}
}
return{
buildObjectFields: function(returnedObj, listItem){ //results:returnedObj, prevItem:listItem
//***
//For SharePoint list data
//***
if (listItem.listName !== "SNB_SecondaryActivityCodes") {
var theList = listItem.listName;
var firstQueryParam = listItem.listObj.codeDigits;
var secondQueryParam = listItem.listObj.codeDescription;
var returnedItems = returnedObj.d.results;
var bigStringOptions = "";
//regex to search for SecondaryFunctionCodes in list names
var pattern = /SecondaryFunctionCodes/;
var isSecFunction = pattern.test(theList);
if(isSecFunction){
bigStringOptions = "<option value='0' selected>Not Applicable</option>";
}else{
bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
}
$.each(returnedItems, function (index, item) {
var first = "";
var second = "";
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key != "__metadata") {
if (key == firstQueryParam) {
first = item[key];
}
if (key == secondQueryParam) {
second = item[key];
}
}
}
}
bigStringOptions += "<option value=" + first + " data-code=" + first + ">" + second + "</option>";
});
var str = theList.toLowerCase();
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
//***
//For other API
//***
} else {
var theList = listItem.listName;
var bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
var returnedItems = returnedObj.value;
for(var i = 0; i < returnedItems.length; i++){
var item = returnedItems[i];
//***
//change event type means the user selected a field
//***
if(listItem.eventType === "change"){
var siteCodeChange = item.SiteCodePc;
if (typeof siteCodeChange === "string" & siteCodeChange != "null") {
siteCodeChange = siteCodeChange < 6 ? siteCodeChange : siteCodeChange.slice(3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeChange + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeChange + ") " + item.Name + "</option>";
snbApp.formmanager.buildSelectSiteLocations(bigStringOptions);
//***
//load event which means this happens when the page is loaded
//***
}else{
var siteCodeLoad = item.SiteCodePc;
if (typeof siteCodeLoad === "string" & siteCodeLoad != "null") {
var siteCodeLoad = siteCodeLoad.length < 4 ? siteCodeLoad : siteCodeLoad.slice(0, 3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeLoad + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeLoad + ") " + item.Name + "</option>";
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
}
}
}
}
};
})();
Form management - called from previous file, gets all select elements on page and appends items from the object in previous file to each select element.
var snbApp = window.snbApp || {};
//Direct interface to the form on the page
snbApp.formmanager = (function(){
var form = {};
form.content_holder = document.getElementById("content_holder");
form.sec_act_codes = document.getElementById("snb_secondary_activity_codes");
form.prim_func_codes = document.getElementById("snb_primary_function_codes");
form.sec_func_codes = document.getElementById("snb_secondary_function_codes");
form.sec_func_nums = document.getElementById("snb_secondary_function_numbers");
form.host_options = document.getElementById("snb_host_options");
form.site_locs_div = document.getElementById("site_locations_div");
form.site_locs = document.getElementById("snb_site_locations");
form.dc_or_off_prem_div = document.getElementById("dc_or_off_premise_div");
form.dc_off_prem_codes = document.getElementById("snb_dc_offpremise_codes");
var snb_secondary_activity_codes = "";
var snb_primary_function_codes = "";
var snb_secondary_function_codes = "";
var snb_secondary_function_numbers = "";
var snb_host_options = "";
var snb_site_locations = "";
var snb_dc_op = "";
//builds the server location hosting options selection
function buildLocationTypeSelector() {
var locationOptionsString = "<option value='0' disabled selected>Select Option</option>";
for (var i = 0; i < locationOptions.length; i++) {
var location = locationOptions[i];
locationOptionsString += "<option value=" + location.hostLocale + " data-code=" + location.code + ">" + location.hostLocale + "</option>";
}
$("#snb_host_options").append(locationOptionsString);
}
function buildSiteLocations(bigString){
if(bigString === undefined){
var siteLocs = document.getElementById("snb_site_locations");
var newOption = document.createElement("option");
newOption.setAttribute("value", 0);
newOption.setAttribute("disabled","disabled");
newOption.setAttribute("checked","checked");
var newText = document.createTextNode("Select Option");
newOption.appendChild(newText);
siteLocs.appendChild(newOption);
} else{
var siteLocs = document.getElementById("snb_site_locations");
siteLocs.innerHTML = bigString;
}
}
return {
form:form,
buildSelectSiteLocations: function(bigString){
buildSiteLocations(bigString);
},
buildForm: function (osType, optObj) {
buildLocationTypeSelector();
buildSecondaryFunctionNumberSelector();
buildSiteLocations();
if(osType === 'windows'){
$("#snb_secondary_activity_codes").append(optObj.windows.secondary_activity);
$("#snb_primary_function_codes").append(optObj.windows.primary_function);
$("#snb_secondary_function_codes").append(optObj.windows.secondary_function);
$("#snb_site_locations").append(optObj.windows.site_location);
$("#snb_dc_offpremise_codes").append(optObj.windows.dc_offpremise);
}else{
$("#snb_secondary_activity_codes").append(optObj.unix.secondary_activity);
$("#snb_primary_function_codes").append(optObj.unix.primary_function);
$("#snb_secondary_function_codes").append(optObj.unix.secondary_function);
$("#snb_site_locations").append(optObj.unix.site_location);
$("#snb_dc_offpremise_codes").append(optObj.unix.dc_offpremise);
}
}
};
})();
Thanks in advance.

Running Two onLoad From an External JavaScript?

I currently have two external scripts for my site that both require the use of onLoad. They are:
One that automatically generates a table of contents:
window.onload = function () {
var toc = "";
var level = 1;
document.getElementById("contents").innerHTML =
document.getElementById("contents").innerHTML.replace(
/<h([\d])>([^<]+)<\/h([\d])>/gi,
function (str, openLevel, titleText, closeLevel) {
if (openLevel != closeLevel) {
return str;
}
if (openLevel > level) {
toc += (new Array(openLevel - level + 1)).join("<ol>");
} else if (openLevel < level) {
toc += (new Array(level - openLevel + 1)).join("</ol>");
}
level = parseInt(openLevel);
var anchor = titleText.replace(/ /g, "_");
toc += "<li><a href=\"#" + anchor + "\">" + titleText
+ "</a></li>";
return "<h" + openLevel + "><a name=\"" + anchor + "\">"
+ titleText + "</a></h" + closeLevel + ">";
}
);
if (level) {
toc += (new Array(level + 1)).join("</ol>");
}
document.getElementById("toc").innerHTML += toc;
};
And another that is used to find certain words in a paragraph and replace them with given JavaScript.
var doc, bod, E, makeLink;
var pre = onload;
onload = function(){
if(pre)pre();
doc = document; bod = doc.body;
E = function(id) {
return doc.getElementById(id);
}
T = function(tag) {
return doc.getElementsByTagName(tag);
}
makeLink = function(node, word, href) {
if(node.innerHTML) {
node.innerHTML = node.innerHTML.replace(word, "<a href='"+href+"'>"+word+'</a>');
}
return false;
}
makeLink(E('testId'), 'Within', 'within.html');
makeLink(E('testId'), 'assuming', 'assuming.html');
}
However, as they're both using onLoad, they don't work together. Is there a way to get them both to function on the same page?
functionA() {
var toc = "";
var level = 1;
document.getElementById("contents").innerHTML =
document.getElementById("contents").innerHTML.replace(
/<h([\d])>([^<]+)<\/h([\d])>/gi,
function (str, openLevel, titleText, closeLevel) {
if (openLevel != closeLevel) {
return str;
}
if (openLevel > level) {
toc += (new Array(openLevel - level + 1)).join("<ol>");
} else if (openLevel < level) {
toc += (new Array(level - openLevel + 1)).join("</ol>");
}
level = parseInt(openLevel);
var anchor = titleText.replace(/ /g, "_");
toc += "<li><a href=\"#" + anchor + "\">" + titleText
+ "</a></li>";
return "<h" + openLevel + "><a name=\"" + anchor + "\">"
+ titleText + "</a></h" + closeLevel + ">";
}
);
if (level) {
toc += (new Array(level + 1)).join("</ol>");
}
document.getElementById("toc").innerHTML += toc;
}
functionB() {
var doc, bod;
//var pre = onload;
//onload = function(){
//if(pre)pre();
doc = document; bod = doc.body;
makeLink(E('testId'), 'Within', 'within.html');
makeLink(E('testId'), 'assuming', 'assuming.html');
}
}
window.E = function(id) {
return doc.getElementById(id);
}
window.T = function(tag) {
return doc.getElementsByTagName(tag);
}
window.makeLink = function(node, word, href) {
if(node.innerHTML) {
node.innerHTML = node.innerHTML.replace(word, "<a href='"+href+"'>"+word+'</a>');
}
return false;
}
Then you call onload from body tag(If you want one to execute before the other, change the order):
<body onload="functionA(); functionB();">
Use addEventListener instead of setting the property of the window object. Here's a MDN page.
You can do something like that:
window.addEventListener('load', function() {
console.log('Loaded 1');
});
window.addEventListener('load', function() {
console.log('Loaded 2');
});
Both of them should fire off.

Uncaught ReferenceError: variable is not defined on onclick function Javascript

Today , i have been read all the topic about this but couldn't come up with a solution that's why i am opening this topic.
This is my function which creates the view and i am trying to have a onclick function which should directs to other javascript function where i change the textbox value.
<script type="text/javascript">
$('#submitbtnamazon')
.click(function(evt) {
var x = document.getElementById("term").value;
if (x == null || x == "" || x == "Enter Search Term") {
alert("Please, Enter The Search Term");
return false;
}
listItems = $('#trackList').find('ul').remove();
var searchTerm = $("#term").val();
var url = "clientid=Shazam&field-keywords="
+ searchTerm
+ "&type=TRACK&pagenumber=1&ie=UTF8";
jsRoutes.controllers.AmazonSearchController.amazonSearch(url)
.ajax({
success : function(xml) {
$('#trackList')
.append('<ul data-role="listview"></ul>');
listItems = $('#trackList').find('ul');
html = ''
tracks = xml.getElementsByTagName("track");
for(var i = 0; i < tracks.length; i++) {
var track = tracks[i];
var titles = track.getElementsByTagName("title");
var artists = track.getElementsByTagName("creator");
var albums = track.getElementsByTagName("album");
var images = track.getElementsByTagName("image");
var metaNodes = track.getElementsByTagName("meta");
//trackId ="not found";
trackIds = [];
for (var x = 0; x < metaNodes.length; x++) {
var name = metaNodes[x]
.getAttribute("rel");
if (name == "http://www.amazon.com/dmusic/ASIN") {
trackId = metaNodes[x].textContent;
trackIds.push(trackId);
}
}
for (var j = 0; j < titles.length; j++) {
var trackId=trackIds[j];
html += '<div class="span3">'
html += '<img src="' + images[j].childNodes[0].nodeValue + '"/>';
html += '<h6><a href="#" onclick="someFunction('
+trackId
+ ')">'
+trackId
+ '</a></h6>';
html += '<p><Strong>From Album:</strong>'
+ albums[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Artist Name:</strong>'
+ artists[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Title:</strong>'
+ titles[j].childNodes[0].nodeValue
+ '</p>';
/*html += '<p><Strong>Created:</strong>'
+ releaseDate
+ '</p>';*/
html += '</div>'
}
}
//listItems.append( html );
$("#track").html(html);
$("#track").dialog({
height : 'auto',
width : 'auto',
title : "Search Results"
});
// Need to refresh list after AJAX call
$('#trackList ul').listview(
"refresh");
}
});
});
</script>
This is my other function where i change the textbox value. it works actually with other values e.g. when i give hardcoded string value. I can see the value in the console but for some reason it gives me the error like :
here the string starts with B is AsinId where i take from amazon. I am definitely in need of help because i am totally stucked.
Uncaught ReferenceError: B00BMQRILU is not defined 62594001:1 onclick
<script type="text/javascript">
function someFunction(var1) {
tracktextbox = document.getElementsByName("trackId");
for (var i = 0; i < tracktextbox.length; i++) {
tracktextbox[i].value = var1;
}
$('#track').dialog('close');
}
</script>
The problem is '<h6><a href="#" onclick="someFunction('+trackId+ ')">', from the error it is clear that trackId is a string value, so you need to enclose it within "" or ''. So try
'<h6><a href="#" onclick="someFunction(\'' + trackId + '\')">'

How to call own function from click method

I know it sounds stupid, but i have no idea how to call my function from "onclick" function?
I made own class and what i wanna do is to call my function inside a class.
I have tried various stuff inside that onclick function:
function(){this.getWidth()}
this.getWidth()
Test.getWidth()
function Datagrid(_parent, _data)
{
this.table = [];
this.parent = $("#"+_parent)[0] ? $("#"+_parent) : ($("."+_parent)[0] ? $("."+_parent) : ($(+_parent)[0] ? $(_parent) : null));
this.data = _data;
this.Datagrid = function(parent,data)
{
this.setParent(parent);
if(data != null)
this.setData(data);
return this;
}
this.setParent = function(parent)
{
return this.parent = $("#"+parent)[0] ? $("#"+parent) : ($("."+parent)[0] ? $("."+parent) : ($(+parent)[0] ? $(parent) : null));
}
this.getParent = function()
{return this.parent;}
this.setData = function(data)
{this.data = data;}
this.buildTable = function()
{
var dtTbl = [];
dtTbl.push('<table class="TimeSheetmainTable" cellpadding="10" cellspacing="0" border="0">');
var style;
//Header//////////////////////
dtTbl.push('<tr class="header">');
for (var cell in this.data.row[0].cell) {
dtTbl.push('<td>' + this.data.row[0].cell[cell].id + '</td>');
}
dtTbl.push('</tr>');
//Content//////////////////////
for(var r in this.data.row)
{
if (r % 2 == 0) { style = 'class="r1" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r1\'"'; }
else { style = 'class="r2" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r2\'"'; }
dtTbl.push('<tr ' + style + ' >');
for(var c in this.data.row[r].cell)
{
dtTbl.push('<td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value + '</td>');
}
dtTbl.push('</tr>');
}
//Footer//////////////////////
dtTbl.push('<tr class="footer">');
for (var cell in this.data.row[0].cell) {
dtTbl.push('<td> </td>');
}
dtTbl.push('</tr></table>');
this.parent.html(dtTbl.join(''));
}
this.buildTableDiv = function()
{
var tableString = [];
//Header//////////////////////
tableString.push('<div class="container"><div class="header"><table><tr id="header">');
for (var cell in this.data.row[0].cell) {
tableString.push('<td>' + this.data.row[0].cell[cell].id + '</td>');
}
tableString.push('</tr></table></div>');
//Content//////////////////////
tableString.push('<div class="content"><table>');
var TD1 = new Object();
var TD2 = new Object();
for(var r in this.data.row)
{
if (r % 2 == 0) { style = 'class="r1" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r1\'"'; }
else { style = 'class="r2" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r2\'"'; }
for(var c in this.data.row[r].cell)
{
if(c == 0)
{ if(TD1.value != this.data.row[r].cell[c].value){
TD1.value = this.data.row[r].cell[c].value;
TD1.show = true;
}
else
TD1.show = false;
}
if(c == 1)
{ if(TD2.value != this.data.row[r].cell[c].value){
TD2.value = this.data.row[r].cell[c].value;
TD2.show = true;
}
else
TD2.show = false;
}
if(TD1.show && c == 0){//First line
tableString.push('<tr id="content" ' + style + ' >');
tableString.push('<td alt="' + this.data.row[r].cell[c].id + '"><input type="button" class="arrow_down" /> ' + this.data.row[r].cell[c].value + '</td>');
for(var c = 0; c < this.data.row[r].cell.length - 1; c++)
{
tableString.push('<td>&nbsp</td>');
}
tableString.push('</tr>');
}
else if(TD2.show && c == 1)//Second line
{
tableString.push('<tr id="content" ' + style + ' >');
tableString.push('<td> </td><td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value + '</td>');
for(var c = 0; c < this.data.row[r].cell.length - 2; c++)
{
tableString.push('<td>&nbsp</td>');
}
tableString.push('</tr><tr id="content" ' + style + ' ><td> </td><td> </td>');
}
else if(!TD2.show && c == 1)//third line (distincts second cells name)
{
tableString.push('<tr id="content" ' + style + ' >');
tableString.push('<td> </td><td alt="' + this.data.row[r].cell[c].id + '"> </td>');
}
else if(c > 1)//Rest filling (not ordered stuff)
{
tableString.push('<td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value.replace(""," ") + '</td>');
}
}
tableString.push('</tr>');
// $(".arrow_down").children(":nth-child(1)").click(function(){alert("test");});
}
tableString.push('</table></div>');
//Footer//////////////////////
tableString.push('<div class="footer"><table><tr id="footer">');
for (var cell in this.data.row[0].cell) {
tableString.push('<td> </td>');
}
tableString.push('</tr></table></div></div>');
this.parent.html(tableString.join(''));
// Setting width to all cells
for (var i in this.data.row[0].cell)
{
cell = parseInt(i)+1;
var h = this.parent.children(":first").children(".header").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
var c = this.parent.children(":first").children(".content").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
var f = this.parent.children(":first").children(".footer").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
var width = h > c ? h : (c > f ? c : f);
this.parent.children(":first").children(".header").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
this.parent.children(":first").children(".content").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
this.parent.children(":first").children(".footer").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
}
// this.activateScroller(0);
}
this.getScrollerWidth = function()
{
var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
// Append our div, do our calculation and then remove it
$('body').append(div);
var w1 = $('div', div).innerWidth();
div.css('overflow-y', 'scroll');
var w2 = $('div', div).innerWidth();
$(div).remove();
return (w1 - w2);
}
this.activateScroller = function(value)
{
var d = [];
d.push('<div style="height: ' + this.parent.children(":first").children(".content").height() + '; width:20px; background:#FFF"><div style="background:#333; height:200"> </div></div>');
this.parent.children(":first").children(".content").scrollTop(value);
}
expandParent = function()
{
alert(this.parent);
}
};
i am kinda makig datagrid based on javascript. i am not allowed to use jQuery UI.
My datagrid is made from tables. now i try to add a button inside a td element like User Name
The problem is that i cant access my function inside my class without making instance. is it even possible to do that without making an instance?
Once your html is generated using your generateHTML function, the handler for onclick on div looses context of what "this" is. To be more specific, this in onclick handler for div refers to that div node in DOM.
To access getWidth method you have to make it available to global context or (better solution) do something like this:
// new version of your generateHTML function
this.generateHTML() {
var str = [];
str.push('<div><input type="button" value="button"/></div>');
var that = this;
$("#testDiv").append(str.join('')).find('button:first').click(function() {that.getWidth()});
}
EDIT:
To further explain how code above works, here's simplified example with comments.
​​Test = function() {
this.generate = function() {
var newnode = $('<button>click me</button>');
$("body").append(newnode);
// "cache" this in a variable - that variable will be usable in event handler
var that = this;
// write event handler function here - it will have access to your methods by using "that" variable
newnode.click(function(e) {
// here this refers to button not Test class
// so we have to "reach" to outer context to gain access to all methods from Test
that.doSomething('learn');
})
}
this.doSomething = function(x) {
alert('do it: '+x);
}
}
// initialize part
// make instance of Test "class"
t = new Test();
// generate the button (clicking on a button will essentialy fire Test.doSomething function in a context of "t"
t.generate();

Categories