I have a bellow code in my stored procedure , but azure is throwing an exception
"maximum allotted time limit exceed" whenever I have while loop with true condition. Unless and until unique validation performed I don't wanna proceed further execution.
if (field.validations.unique != undefined && field.validations.unique) {
var gotResponse = false;
var query = "select * from root r where r." + field.name + "='" + record[field.name] + "' AND r.obj_type = '" + record.obj_type + "'";
var isAccepted = collection.queryDocuments(collectionLink, query, {}, function (err, existingDocs, responseOptions) {
if (existingDocs.length > 0 && existingDocs[0].id != record.id) {
if (!record.error['unique'])
record.error['unique'] = [];
record.error['unique'].push(field.name);
}
gotResponse = true;
});
while(true){
if(gotResponse ) break;
}
}
Related
Im trying to create a function that lets me search and order a list using Node and SQLite3. Im not quite sure what I am doing wrong, but when I include the sort parameter the code stops working and I get "Error: SQLITE_ERROR: Near "?": syntax error".
This is the code.
exports.search = function(name, sort, sortAscDesc, cb) {
var sqlQuery = "SELECT * FROM Crimestat";
if (name != undefined) {
name = "%" + name + "%";
sqlQuery += " WHERE municipacility LIKE ?";
}
if (sort != undefined) {
if (sortAscDesc != undefined) {
sqlQuery += " ORDER BY ? ?";
} else {
sqlQuery += " ORDER BY ASC";
}
}
console.log("sql query " + sqlQuery)
db.all(sqlQuery, name, sort, sortAscDesc, function(err, row) {
if (row == undefined) {
console.log("error " + err)
cb(false);
} else {
cb(row);
}
});
Thank you in advance
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.
I consume a SOAP who use a PasswordDigest authentification.
I use with succes this library: https://github.com/vpulim/node-soap
I run this code on Debian with nodejs version v0.10.29 and it's work.
Now i need to make it run on a windows computer with nodejs v6.6.0, and its not working anymore.
I have the following messages:
The security token could not be authenticated or authorized
I suspect a problem with the crypto lib, this code maybe:
"use strict";
var crypto = require('crypto');
exports.passwordDigest = function passwordDigest(nonce, created, password) {
// digest = base64 ( sha1 ( nonce + created + password ) )
var pwHash = crypto.createHash('sha1');
var rawNonce = new Buffer(nonce || '', 'base64').toString('binary');
pwHash.update(rawNonce + created + password);
return pwHash.digest('base64');
};
From https://github.com/vpulim/node-soap/blob/master/lib/utils.js
Ok, so here's the way I've worked around it:
The SOAP library has a function for building the WSSE security header, which is placed in soap/lib/security/templates/WSSecurity.js.
The problem for me that the UsernameToken it was placing in the header was inconsistent with the one that soapUI was using and actually getting results (in my example).
Orignal code:
"<wsse:UsernameToken xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" wsu:Id=\"SecurityToken-" + created + "\">
While what I needed was:
<wsse:UsernameToken wsu:Id="UsernameToken-<token>">
To get the proper token I've used WSSE library from npm (https://www.npmjs.com/package/wsse).
All I had to do was include the package, define the token as in the readme:
const wsse = require('wsse');
const token = wsse({ username: '<username>', password: '<password>' })
Then call token.getNonce() for the proper token and token.getPasswordDigest() for the EncodingType property in the header.
After that everything works as intended.
Hope that helps!
I have pushed module using #MTM answer.
Please have a look
https://www.npmjs.com/package/wssecurity-soap
Code for fixing it, in case anyone wants to review (its same as soap wssecurity auth implementation including fix)
var crypto = require('crypto');
var wsse = require('wsse');
var validPasswordTypes = ['PasswordDigest', 'PasswordText'];
function WSSecurity(username, password, options) {
options = options || {};
this._username = username;
this._password = password;
if (typeof options === 'string') {
this._passwordType = options ?
options :
'PasswordText';
options = {};
} else {
this._passwordType = options.passwordType ?
options.passwordType :
'PasswordText';
}
if (validPasswordTypes.indexOf(this._passwordType) === -1) {
this._passwordType = 'PasswordText';
}
this._hasTimeStamp = options.hasTimeStamp || typeof options.hasTimeStamp === 'boolean' ? !!options.hasTimeStamp : true;
if (options.hasNonce != null) {
this._hasNonce = !!options.hasNonce;
}
this._hasTokenCreated = options.hasTokenCreated || typeof options.hasTokenCreated === 'boolean' ? !!options.hasTokenCreated : true;
if (options.actor != null) {
this._actor = options.actor;
}
if (options.mustUnderstand != null) {
this._mustUnderstand = !!options.mustUnderstand;
}
}
WSSecurity.prototype.toXML = function() {
this._token = wsse({
username: this._username,
password: this._password
})
function getDate(d) {
function pad(n) {
return n < 10 ? '0' + n : n;
}
return d.getUTCFullYear() + '-'
+ pad(d.getUTCMonth() + 1) + '-'
+ pad(d.getUTCDate()) + 'T'
+ pad(d.getUTCHours()) + ':'
+ pad(d.getUTCMinutes()) + ':'
+ pad(d.getUTCSeconds()) + 'Z';
}
var now = new Date(this._token.getCreated());
var created = this._token.getCreated() ;
var timeStampXml = '';
if (this._hasTimeStamp) {
var expires = getDate( new Date(now.getTime() + (1000 * 600)) );
timeStampXml = "<wsu:Timestamp wsu:Id=\"Timestamp-"+created+"\">" +
"<wsu:Created>"+created+"</wsu:Created>" +
"<wsu:Expires>"+expires+"</wsu:Expires>" +
"</wsu:Timestamp>";
}
var password, nonce;
if (this._hasNonce || this._passwordType !== 'PasswordText') {
var nHash = crypto.createHash('sha1');
nHash.update(created + Math.random());
nonce = nHash.digest('base64');
}
if (this._passwordType === 'PasswordText') {
password = "<wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">" + this._password + "</wsse:Password>";
if (nonce) {
password += "<wsse:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">" + nonce + "</wsse:Nonce>";
}
} else {
password = "<wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest\">" + this._token.getPasswordDigest() + "</wsse:Password>" +
"<wsse:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">" + this._token.getNonceBase64() + "</wsse:Nonce>";
}
return "<wsse:Security " + (this._actor ? "soap:actor=\"" + this._actor + "\" " : "") +
(this._mustUnderstand ? "soap:mustUnderstand=\"1\" " : "") +
"xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">" +
timeStampXml +
"<wsse:UsernameToken wsu:Id=\"UsernameToken-" + created +"\">"+
"<wsse:Username>" + this._username + "</wsse:Username>" +
password +
(this._hasTokenCreated ? "<wsu:Created>" + created + "</wsu:Created>" : "") +
"</wsse:UsernameToken>" +
"</wsse:Security>";
};
module.exports = WSSecurity;
I'm trying to get every single item from all lists within a SharePoint site. All of the docs and answered questions I've found in order to do this usually explain how to get all lists or all items from one list, but not every item in all lists within a site context.
I have my code below and I am able to get all lists fine, my biggest struggle is getting the items and not only from the last list (for some reason, it kept on doing this as I tested in the console - this version would probably just produce null errors instead since I made changes from before).
var allInfo = "";
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getAllListsAndItems);
function getAllListsAndItems() {
var context = new SP.ClientContext('https://mysites.sprcompanies.com/personal/cnorman/charpractice/');
var web = context.get_web();
var lists = web.get_lists();
context.load(lists);
context.executeQueryAsync(onQuerySucceeded, onQueryFailed);
function onQuerySucceeded(sender, args) {
var listEnumerator = lists.getEnumerator();
while (listEnumerator.moveNext()) {
var list = listEnumerator.get_current();
allInfo += " List: " + list.get_title() + "\n";
if (list.get_itemCount() > 0) {
var query = new SP.CamlQuery();
query.set_viewXml('<View></View>');
var items = list.getItems(query);
context.load(items);
context.executeQueryAsync(onSuccess, onFail);
function onSuccess(sender, args) {
var itemsEnumerator = items.getEnumerator();
while (itemsEnumerator.moveNext()) {
var item = itemsEnumerator.get_current();
}
}
function onFail(sender, args) {
console.log('Request on items failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
}
}
console.log(allInfo);
}
function onQueryFailed(sender, args) {
console.log('Request on lists failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
}
I know the general problem area is here:
var itemsEnumerator = items.getEnumerator();
while (itemsEnumerator.moveNext()) {
var item = itemsEnumerator.get_current();
}
I originally had it append to allInfo, but all it does is produce 'not initialized' errors. I first thought that I just wasn't loading the items properly, but after testing it in the console, it does display the item collection objects so that's why I think it has something to do with the above.
Couldn't I just use a for loop to cycle through the items instead? I only need the titles of each item. I tried a for and a for in, but it again results in errors. So it's really how I'm accessing each item (using the wrong properties). Thank you in advance!
Edit:
So I put this in the item onSuccess block instead:
if (items.get_item("Title") == null) {
items.get_data().forEach(function(item) {
console.log(item.get_item('URL').get_description());
});
}
else {
items.get_data().forEach(function(item) {
console.log(item.get_item('Title'));
});
}
Both would get the 'title' of an item whether it's a regular item or a link item - the problem is that it only get the items of the last list and repeats those multiple times instead of going through every list.
For those interested in how I got the answer:
var allInfo = "";
var listsArray = [];
var itemsArray = [];
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getAllListsAndItems);
function getAllListsAndItems() {
var context = new SP.ClientContext(SiteURL);
var web = context.get_web();
var lists = web.get_lists();
context.load(lists);
context.executeQueryAsync(onQuerySuccess, onQueryFailure);
function onQuerySuccess(sender, args) {
var listEnumerator = lists.getEnumerator();
while (listEnumerator.moveNext()) {
var list = listEnumerator.get_current();
listsArray.push(list.get_title());
}
for (var i = 0; i < listsArray.length; i++) {
var query = new SP.CamlQuery();
query.set_viewXml('<View></View>');
itemsArray[i] = lists.getByTitle(listsArray[i]).getItems(query);
itemsArray.push(itemsArray[i]);
context.load(itemsArray[i]);
}
context.executeQueryAsync(onSuccess, onFailure);
function onSuccess(sender, args) {
for (var i = 0; i < itemsArray.length; i++) {
if (listsArray[i] != "Master Page Gallery") {
allInfo += " List: " + listsArray[i] + "\n";
itemsArray[i].get_data().forEach(function(item) {
if (item.get_item("Title") == null) {
allInfo += " \t Item: " + item.get_item('URL').get_description() + "\n";
}
else if (item.get_item("Title") != null) {
allInfo += " \t Item: " + item.get_item("Title") + "\n";
}
else {
console.log("Something's wrong with this one.");
}
});
}
}
console.log(allInfo);
}
function onFailure(sender, args) {
console.log('Request on items failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
}
function onQueryFailure(sender, args) {
console.log('Request on lists failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
}
So basically I had to push every list that was loaded into an array then use that to load items from each one at a time because originally looping through it did not work since it only picked up the last list. This would produce a structure like this:
List
Item
Item
...
List
Item
Item
...
...
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).