Javascript Variable Scope Confusion - javascript

In the following code snippet I've declared the variable "id" within the submit function. I attempt to assign a value to it within a nested function but it doesn't appear to be within scope and I don't know why.
$(document).ready(function() {
if (typeof(localStorage) == 'undefined' ) {
alert('Your browser does not support HTML5 localStorage. Try upgrading.');
}
else {
$("#logForm").submit(function(){
var id;
chrome.bookmarks.getRecent(1, function(mostrecent) {
getLastId(mostrecent);
});
function getLastId(mostrecent) {
mostrecent.forEach(function(mostrecent) {
lastId = mostrecent.id;
alert(lastId + ' was last id');
id = lastId;
})
}
alert(id + ' outside function');
Bonus Question - If you know a better way to pull the last-used id from chrome for a bookmark would love to know what it is. I had to pull recent which doesn't account for the possibility of an added and then deleted last bookmark which would have incremented the index.

This should do it:
$("#logForm").submit(function() {
var id;
chrome.bookmarks.getRecent(1, function(arr) {
id = arr.pop().id;
});
// do stuff with id
});

Related

Javascript returning multiple checkbox values

I'm having some trouble trying to get multiple checkbox values. It currently is working, just not in the way I wanted/was hoping it would. Right now anything checked is appended to the bottom of the body and not inline with the function it was aiming to be inserted into.
I'm trying to avoid using JQuery or anything except JavaScript as it's all we've currently covered in our class.
function favMedia(media){
var media = document.forms['mediapref']['media'].value;
return media;
}
function pets(pet){
var pet = document.getElementsByName('pets')
for (var checkbox of pet){
if (checkbox.checked)
document.body.append(checkbox.value + ' ');
}
}
function about(text){
var info = document.forms['personal']['about'].value;
return info;
}
function infoForm(media, pet, text){
document.getElementById('infoset').innerHTML = favMedia(media) + "<br>" + pets(pet) + "<br>" + about(text);
}
Is there some way I can assign it just to a single variable to return and then throw into the last function?
Also please give me any tips or improvements on any aspect of the functions if you have any.
Put it in a string that you return from the function.
function pets(pet) {
var pet = document.querySelector('[name="pets":checked');
let selected = [...pet].map(p => p.value);
return selected.join(', ');
}

CRM Xrm.Page.ui.formSelector.items.get() Returning Null

I wrote javascript code and added it as a form on load event of entity(contact). In that Code I want to navigate from the opening form to another form.
For previous developments, I'm trying to get the id of the opening form which I need in order to navigate.
Code as shown below.
var id = Xrm.Page.ui.formSelector.getCurrentItem().getId();
if (itemid != null)
Xrm.Page.ui.formSelector.items.get(id).navigate();
Xrm.Page.ui.formSelector.getCurrentItem() function returns a null value. It doesn't get the item so I can't get the value. What's wrong with that code, what am I missing?
Thanks for replies in advance.
You are assigning the value to id variable but checking itemid in your IF condition.
In if condition just replace the if (itemid != null) with if (id != null)
To test your JavaScript. You can run following function:
var formItem = Xrm.Page.ui.formSelector.getCurrentItem();
if (formItem != null)
{
var itemId = formItem.getId();
var itemLabel = formItem.getLabel();
alert(itemId + " | " itemLabel);
}
else
{
alert("Unable to get current form");
}
Finally, to switch between form, following is very useful function which takes the form name as parameter. you can make changes to use form Id if you like.
function redirectToForm(formName) {
var currentForm = Xrm.Page.ui.formSelector.getCurrentItem();
if (currentForm != null) {
if (currentForm.getLabel().toLowerCase() != formName.toLowerCase()) { //make sure it's not already this form
var availableForms = Xrm.Page.ui.formSelector.items.get();
for (var i in availableForms) {
var form = availableForms[i];
if (form.getLabel().toLowerCase() == formName.toLowerCase()) {
form.navigate();
}
}
}
}
}
In My case, i prefer send the form name as parameter of a kind function such as constructor via load form function.
in the javascript code:
var Formname = "Default";
function Initialize(formname)
{
Formname = formname;
}
In customization of Form, in the onload function, you set this variable and this way remove the dependece from for selector component.
I hope that this solution can help many.
I took it up a notch and wrote the following post. You might find it interesting.
http://totbcrm.blogspot.co.il/2014/08/working-with-multiple-forms.html

The collection has not been initialized - Sharepoint Javascript

I'm getting the following error when attempting to get an enumerator for a collection of lists: "Uncaught Error: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."
It happens on the line var listEnumerator = lists.getEnumerator(); it seems to me that there is an issue in my attempt to load lists into the client object with context.load(lists);
Here's the portion of my code that's causing the problem. I've marked the place just before the error is thrown.
//____________________________Required function for accessing the host site's info.___________________________________
function getQueryStringParameter(param) {
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == param) {
return singleParam[1];
}
}
}
//____________________________Begin checking for list_________________________
function checkForList(listToFind, typeOfListToCreateIfTheListIsMissing)
{
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
var hostcontext = new SP.AppContextSite(context, hostUrl);
var hostweb = hostcontext.get_web();
var lists = hostweb.get_lists();
context.load(lists);
context.executeQueryAsync(checkIfListExistsUsingEnumerator(listToFind, lists, hostweb, typeOfListToCreateIfTheListIsMissing), onQueryFailed);
}
//Failed to get lists for some reason
function onQueryFailed(sender, args) {
alert('We failed to retrieve lists. \n' + args.get_message() + '\n' + args.get_stackTrace());
}
//____________________________Does list exist?____________________________
function checkIfListExistsUsingEnumerator(listToFind, lists, hostweb, typeOfList)
{
var listExists = false;
//!!!!!!!!!!!!!!! ERROR HERE !!!!!!!!!!!!!!!!
var listEnumerator = lists.getEnumerator();
var title;
while (listEnumerator.moveNext())
{
title = listEnumerator.get_current().get_title();
if (title == listToFind)
{
listExists = true;
}
}
if (!listExists)
{
alert("It appears that a required list does not already exist. \nClick ok, and we'll automatically create one for you.");
//Create a new list
createList(listToFind, hostweb, typeOfList);
}
else if (listExists)
{
//Do nothing.
}
}
//____________________________If it doesn't, create one on the local site____________________________
function createList(nameOfNewList, hostweb, typeOfList) {
var listCreationInfo = new SP.ListCreationInformation();
listCreationInfo.set_title(nameOfNewList);
if (typeOfList === "events")
{
listCreationInfo.set_templateType(SP.ListTemplateType.events);
}
else if (typeOfList === "contacts")
{
listCreationInfo.set_templateType(SP.ListTemplateType.contacts);
}
var lists = hostweb.get_lists();
var newList = lists.add(listCreationInfo);
context.load(newList);
context.executeQueryAsync(onListCreationSuccess, onListCreationFail);
}
function onListCreationSuccess() {
alert('List created successfully!');
}
function onListCreationFail(sender, args) {
alert('Failed to create the list. ' + args.get_message());
}
I've looked at this question sharepoint javascript collection not initialized error which seems to be fairly similar to mine, but I'm having trouble implementing the solution provided there, making me think my error may be have a different cause.
I've also tried querying for the lists inside of the function that is throwing the error, but that doesn't seem to solve anything.
For a little background, these functions are attempting to read all lists from the app's host site, check to see if a specified list exists, and create a list if no matching list exists. If there's a better way of doing that than what I'm attempting, I'd be open to that too.
Any pointers?
Some things I've tried that don't seem to work:
Changing the Asynchronous query
context.executeQueryAsync(checkIfListExists(listToFind, hostweb, typeOfListToCreateIfTheListIsMissing), onQueryFailed);
to a Synchronous one.
context.executeQuery(checkIfListExists(listToFind, hostweb, typeOfListToCreateIfTheListIsMissing), onQueryFailed);
I've figured out an alternate, and shorter way to method of achieving the same goal I was trying to achieve before.
Instead of checking to see if a list does not already exist, I just try to create a list, and the Query fails to create a list if one is already there. (That's good because I don't want to overwrite the list if it is already there.)
I'm not totally sure if there are any undesired side effects of what I'm doing here, but in my tests it produced the desired behavior.
//____________________________Required function for accessing the host site's info.___________________________________
function getQueryStringParameter(param) {
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == param) {
return singleParam[1];
}
}
}
//____________________________Create a list if one does not already exist_________________________
function createList(listToCreate, typeOfList)
{
// Create an announcement SharePoint list with the name that the user specifies.
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
var hostContext = new SP.AppContextSite(currentContext, hostUrl);
var hostweb = hostContext.get_web();
var listCreationInfo = new SP.ListCreationInformation();
listCreationInfo.set_title(listToCreate);
if (typeOfList === "events")
{
listCreationInfo.set_templateType(SP.ListTemplateType.events);
}
else if (typeOfList === "contacts")
{
listCreationInfo.set_templateType(SP.ListTemplateType.contacts);
}
var lists = hostweb.get_lists();
var newList = lists.add(listCreationInfo);
currentContext.load(newList);
currentContext.executeQueryAsync(onListCreationSuccess, onListCreationFail);
}
function onListCreationSuccess() {
alert("We've created a list since one doesn't exist yet." );
}
function onListCreationFail(sender, args) {
alert("We didn't create the list. Here's why: " + args.get_message());
}

Help modify a javascript - need to open link instead of displaying result

I'm trying to modify the code from this script. Basically I'm trying to get the script to send the browser to another page rather than display the results in a div.
This is the code in question:
<script type="text/javascript">
function openOneSlot() {
SpinningWheel.addSlot({1: 'First', 2: 'Second'});
SpinningWheel.setCancelAction(cancel);
SpinningWheel.setDoneAction(done);
SpinningWheel.open();
}
function done() {
var results = SpinningWheel.getSelectedValues();
document.getElementById('result').innerHTML = 'values: ' + results.values.join(' ') + '<br />keys: ' + results.keys.join(', ');
}
function cancel() {
document.getElementById('result').innerHTML = 'cancelled!';
}
window.addEventListener('load', function(){ setTimeout(function(){ window.scrollTo(0,0); }, 100); }, true);
</script>
I've changed the 'done' function to as follows:
function done() {
var results = SpinningWheel.getSelectedValues();
if (SpinningWheel.getSelectedValues() == "1,First")
{
window.location="first.html";
}
else if (SpinningWheel.getSelectedValues() == "2,Second")
{
window.location="second.html";
}
else
{
alert("Damn, Still not working..");
}
But now I'm lost as I'm very new to javascript.. Can anyone help the noob to get this working?
:)
Try this:
function done() {
var results = SpinningWheel.getSelectedValues();
if (results.values[0] == "First")
{
window.location.href="first.html";
}
else if (results.values[0] == "Second")
{
window.location.href="second.html";
}
else
{
alert("Damn, Still not working..");
}
The returned values appear to be an array of all the slots. Since yours has only one slot, I'm only looking at the first array position of the "results.values" array.
Try location.href instead of window.location
Note that this particular thing (changing page) is done differently across different browsers so you should google "javascript redirect " if you run into trouble on a particular browser
Look at what is returned by SpinningWheel.getSelectedValues(). It is an object with two properties keys and values. Therefore, it will not equal "1,First". Check into what is in those properties, and base your conditionals on those.
To pass your variables through, use the following syntax:
window.location = "first.html?var1Name=" + var1 + "&var2Name=" + var2;
To get the value of those variables on your first.html and second.html pages, you can use the window's query string to get hold of their values:
http://www.eggheadcafe.com/articles/20020107.asp
You would want to look at the window.location.search property.

jQuery Dynamic Function and Variable

I am trying to create a function that handles the 'keyup' event for several input fields and passes the input value to a php script. Here's the code I have so far
$(document).ready(function () {
$("#email").keyup(function () {
val = $("input#email").val();
what = 'email';
aFunction(val, what);
});
});
function aFunction(val, what) {
var dataString = what + '=' + val;
var error = "email_check";
$.post("key.php", dataString, function (data) {
//if (data.[error] == 'invalid'){
if (data.email_check == 'invalid') {
$("#ppp").html('error');
} else {
$("#ppp").html('good to go');
}
}, "json");
//return false;
}
When I uncomment
//if (data.[error] == 'invalid'){
and comment out
if (data.email_check == 'invalid'){
My the script doesnt execute and js file doesn't load into the firebug script console - I assume means there's an error because when I undo that and refresh I can view it. I've tried added single and double quotes to the variable. Also, it would be helpful if there was a way to see what the is error is, but I don't know how to do that.
Your primary problem here is that you should use either dot notation ("data.error") or array notation ("data['error']") but not both ("data.['error']").
Javascript does not support braces in identifiers.
If the key is actually just error, you can write if (data.error == 'invalid').
If it is [error], you'll need to write if (data['[error]'] == 'invalid)`.
To see syntax errors, go to Firebug's Console tab.

Categories

Resources