How to make a Global Variable with User Input? - javascript

I am making a program where I have a user input where the user types in their cat's name, and then I want the name to appear in the text throughout the program. Here is my code, it is in Javascript:
var catName = getText("nameInput");
onEvent("startBtn", "click", function(event) {
setScreen("feedingScreen");
setText("feedingText", catName+" is hungry! Give "+catName+" some food!
Click fish to feed.");
});
Whwn I run this program, however, the cat name does not appear in the text. How can I make it where the text does show up?

If the catName variable is going to be used for a long time, I'd consider using localStorage to store it and retrieve it whenever I want (even when the user leaves the page and comes back).
Example :
function setCatName(name) {
window.localStorage.setItem('catName', name);
}
function getCatName() {
return window.localStorage.getItem('catName');
}
If you don't want that though, you could store it in the window object. Take note that it's considered bad practice (but so are global variables in general).
Example :
function setCatName(name) {
window.catName = name;
}
function getCatName() {
return window.catName;
}
UPDATE :
It's funny because the examples on Mozilla's Docs use localStorage to set and retrieve a cat's name too :
localStorage documentation

Related

How would one set the initial value of an editable div?

So, I've got a notepad extension for Google Chrome that syncs and displays stored notes from a user. Currently my problem is as follows.
When the extension is run for the first time after download, the word 'undefined' is displayed in the editable div (id = edit_notepad). I want it to just be blank instead of displaying anything. Obviously, I know its undefined because the user hasn't been able to add any text yet.
Picture of what's displayed on initial run:
From my content script, here are my chrome.storage get and set functions (which do work):
document.body.onload = function() {
chrome.storage.sync.get("edit_notepad", function(items) {
if (!chrome.runtime.error) {
console.log(items);
document.getElementById("edit_notepad").innerHTML = items.edit_notepad;
}
});
}
document.getElementById("edit_notepad").onkeyup = function() {
var d = document.getElementById("edit_notepad").innerHTML;
chrome.storage.sync.set({ "edit_notepad" : d }, function() {
if (chrome.runtime.error) {
console.log("Runtime error.");
}
});
}
I presume I'm going to need some sort of if statement, but after hours of playing around, I'm lost as to what exactly it'd contain. The issue I've kept running into is that whatever I set the initial value of edit_notepad to, it always reverts back to "undefined" even when a user has written some notes! e.g. "This is a notes test" would revert back to "undefined" when the notepad is closed and reopened.
Well, an easy way to do this would be to specify a default value in your chrome.storage.sync.get(). Doing so would apply the default value when the key does not exist in the storage. However, given that you are replacing any contents which might already exist, the better solution would be not to set the contents when you have no value, or an invalid value, stored. The only valid value will be a string. This will prevent you from overwriting any default value supplied by the webpage when you have no value stored. Thus, an if statement something like the following should work (alternately, you could test for !== 'undefined':
document.body.onload = function() {
chrome.storage.sync.get("edit_notepad", function(items) {
if (!chrome.runtime.error) {
console.log(items);
if(typeof items.edit_notepad === 'string') {
document.getElementById("edit_notepad").innerHTML = items.edit_notepad;
}
}
});
}
Note: Storing the contents of the editable <div> on every key will result in many users running into both the MAX_WRITE_OPERATIONS_PER_MINUTE and MAX_WRITE_OPERATIONS_PER_HOUR quotas. You will need to have some other criteria for writing to storage.sync. Perhaps you could temporarily store the value in storage.local and only to storage.sync every couple of minutes.

iBooks Author/iAd Producer Widget User Text Disappears

I'm using iAd producer to create HTML widgets for iBooks I'm making using iBooks Author. I've done some research and learned that I can have user input saved into local storage by way of a variable that is called every time the widget is opened. This is great except for the new problem of having to create hundreds of text box widgets all with different variables so I can use these text boxes on multiple pages. Is there a way for me to automate this using Java Script? One idea I had was to use a "while" function to tell the script to ++ the variable if the one it tried to use was not empty. Example: the variable "001" was already used so the code would ideally set the next user text to variable "002". Preferably, I'd like to be able to create one widget with this code that I could reuse anywhere else.
Here is the code I'm currently using:
/*Widget code*/
this.onViewControllerViewWillAppear = function (event) {
var theValue = this.outlets.textField;
if (localStorage.getItem("theKey102") === null) {
theValue.value = "";
} else {
theValue.value = localStorage.getItem("theKey102");
}
};
/*This is the code for one of the text boxes I'm using */
this.onControlValueChange = function (event) {
var theValue = this.viewController.outlets.textField;
localStorage.setItem("theKey102", theValue.value);
};

Call Functions Based On Query String Using JavaScript

On my web app, the user is asked a question and can choose only one of two answers. Yes or no. A query string is created based on their answer.
The following code carries the query string through the URL of every page:
var navlinks = document.getElementsByClassName("qString");
$(navlinks).prop("href", function() { return this.href + location.search; })
There are only 2 query strings, ?choice=yes and ?choice=no.
Once the user is taken through the app, if they navigate to either park01.html, park02.html, or park03.html from any other page, data will be pulled accordingly via a called function().
Here's my concept in pseudocode:
// I assume I should store specific html pages to a variable
var parkPages = ["park01.html", "park02.html", "park03.html”];
if (user clicks on specified html pages stored in variable) {
and the url contains = ?choice=yes;
Then call these functions: funcA(), funcB(), funcC();
}
else {
the url contains = ?choice=no;
Then call these functions: funcD(), funcE(), funcF();
}
Does the concept make sense? And what does the syntax look like?
If you're simply looking for a concrete translation of your pseudocode into JavaScript, based on your last comment, this should be what you need:
if (location.search === "?choice=yes") {
funcA();
funcB();
funcC();
}
else {
funcD();
funcE();
funcF();
}
Though at this stage, I'd recommend spending less time here and more on instructional/tutorial based websites.

Need to change the function name in JS, trying to keep it from breaking

I'm no javascript guru, I'm having to call an external JS file twice in one page. The JS file includes a function. Having this function called twice (once in each JS include) breaks the functionality. So I thought I'd modify the 2nd instance to a different function name. This works to allow the first instance to work correctly but breaks the 2nd one (The one with the function changed).
The function name is address and I'm trying to work just exactly what else needs to be modified in this script to reflect the name change. I fear there are other mentions of "address" that is legitimate and not associated with the function name. I'm at my wits end and am just not sure. Anyone care to look at this JS and help me find which instances of the word address need to be changed to correctly reflect the one function and var name?
/**
* execute part
*/
$(document).ready(function(){
address.bindZipcodeFind();
});
var address = {
bindZipcodeFind: function(){
$('.zipcode-searcha').click(function(){
$('.zipcode-search-resulta').text("로딩중...");
$.get('http://www.nuvonoir.com/postalcode2/zipsearch-action.php',{
query: $('#dongNamea').val()
},function(data){
$('.zipcode-search-resulta').html(data);
address.bindPutAddress();
})
});
},
bindPutAddress: function(){
$('.zipcode-search-resulta a').click(function(){
$('[id=zipcode1a]').val($(this).parent().parent().find('.postcd1').text());
$('[id=zipcode2a]').val($(this).parent().parent().find('.postcd2').text());
$('[id=OrdAddra]').val(address.remove_useless_addr($(this).parent().parent().find('.address').text()));
address.hideZipcodeFinder();
$('[name=addr]').focus();
return false;
});
},
remove_useless_addr: function(address){
if(address.indexOf('~') != -1){
address = address.split(' ').slice(0,-1).join(' ');
}
return address;
},
hideZipcodeFinder: function(){
$('.zipcode-findera').slideUp();
}
}
If you have no way to mitigate including code twice, then there's the only option: write that function was called elsewhere:
global variable
invisible element with certain id
or even more magic things:
field in document object or document root node (html/body)
location hash (URL part after #)
cookie/sessionStorage based on document.lastModified (it is equal to page generating time on server) or anything remaining stable within one page load.
Example using global variable:
function once() {
if (window.myOnceFuncIsCalled) return;
// do the main work
window.myOnceFuncIsCalled = true;
}

Variable not updating in script string, yet it updates

Very confused here.
I have a search box which reads a list of school names from my database. When I select a school, the id (from the db) gets put in a hidden textbox.
I also have a search box which reads a list of courses from my database. However, I made the query so that it only reads the courses from the selected school.
It does that, in theory.
I was planning to pass the school id, which I grab from the hidden box, to the search script which in turn passes it to my database query. However, the variable I put my school id in doesn't seem to be updating.. yet it does. Let me explain.
I come on the page. The school for my test account has id 1. The id number in my hidden box is indeed 1. I search for a school which I know has some courses assigned to it: the id number in the box changes to 3.
I have a JS variable called school_id which I declared outside of my $(document).ready. I assume that means it's global (that's what I got taught even though SO told me once it isn't really the correct way to do this. Still have to look into that). I wrote a function which updates this variable when the school search box loses focus:
$("#school").blur(function() {
school_id = $("#school_id").val();
});
A quick javascript:alert(school_id); in my browser bar also shows the updated variable: it is now 3 instead of 1.
Onto the search script part of my page (excerpt of the script):
script:"/profiel/search_richting?json=true&limit=6&id=" + school_id + "&"
As you can see, I pass the school_id variable to the script here. However, what seems to be happening is that it always passes '1', the default variable when the page loads. It simply ignores the updated variable. Does this string get parsed when the page loads? In other words, as soon as the page loads, does it actually say &id=1? That's the only idea I can come up with why it would always pass '1'.
Is there a way to make this variable update in my script string? Or what would be the best way to solve this? I'm probably missing out on something very simple here again, as usual. Thanks a lot.
EDIT
Updated per request. I added a function getTheString as was suggest and I use the value of this function to get the URL. Still doesn't work though, it still seems to be concatenating before I get a chance to update the var. HOWEVER, with this code, my ajax log says id:[object HTMLInputElement], instead of id:1. Not sure what that means.
<script type="text/javascript">
var school_id;
$(document).ready(function() {
$("#school").blur(function() {
school_id = $("#school_id").val();
});
// zoekfunctie
var scholen = {
script:"/profiel/search_school?json=true&limit=6&",
varname:"input",
json:true,
shownoresults:false,
maxresults:6,
callback: function (obj) { document.getElementById('school_id').value = obj.id; }
};
var as_json = new bsn.AutoSuggest('school', scholen);
var richtingen = {
script: getTheString(),
varname:"input",
json:true,
shownoresults:true,
maxresults:6
};
var as_json2 = new bsn.AutoSuggest('studierichting', richtingen);
});
function getTheString() {
return "/profiel/search_richting?json=true&limit=6&id=" + school_id + "&";
}
</script>
This is because the URL is static, it is not updated as the ID changes.
You should update the URL as part of the code you wrote to get the ID:
$("#school").blur(function() {
school_id = $("#school_id").val();
// update URL here ...
});
Aren't you concatenating script:"/profiel/search_richting?json=true&limit=6&id=" + school_id + "&" before the event is fired and the var updated?
Okay. So the problem was my third party plug-in instead of the code I wrote. I fixed this by editing the code of the autoSuggest plugin so it now includes my id field in the AJAX request.
var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp)+"&id="+ $("#school_id").val();
Thanks to everyone who tried to help me out!

Categories