Keeping a variable and string together in localstorage - javascript

Hey i want to store a piece of text plus a variable in localstorage.
This may seem a bit vague so here is what i mean with this:
var something = "text";
localStorage.setItem("localstorage", '"sometext"+something');
function functionz()
{
var displayed = localStorage.localstorage;
alert(displayed);
}
I want to make sure that displayed will display this text: sometexttext
I had it already working by storing "sometext"+something in a variable like this:
var something = "text";
localStorage.setItem("localstorage", '"sometext"+something');
function functionb()
{
var thetext = "sometext"+something;
alert(thetext);
}
The second version will give you: (sometexttext), and the first one will give you ("sometext"+something) as raw text. This is ofcourse not what i want and i wonder how i can make it so that it can be stored in localstorage and still display the second result.
Thanks in advance

Related

Free Code Camp weather app, toggle won't work

Here is my Javascript code.
$("#changetemp").click(function () {
var temp = $("#temperature").html;
var final_letter = temp[temp.length-1];
$("#temperature").html(function ()
{if (final_letter == "F") {return celsius;}
else {return fahrenheit;}});});
});}});});
It is supposed to toggle the temperature between celsius and fahrenheit but does a big fat nothing. I've googled and changed a few things (e.g. gone between val, html and text, and tried charAt but I can't get it to do anything, let alone the right thing. Any suggestions would be very welcome.
Edit: "#changetemp" is the button you click to toggle between temperature (ideally).
"#temperature" is where the temperature displays (and it does, but then won't change).
Also tried:
console.log(final_letter); (which gave the correct letter in the console)
console.log(celsius); (which reports as 'undefined') as does console.log(fahrenheit);
These two are defined earlier via a JSON
$.getJSON( url, function(location){ var celsius =
$("#temperature").html(Math.round(location.main.temp - 273) + "°C");});
and I tried to make them be global variables by putting
var celsius;
var fahrenheit;
after the beginning of the first function (which surrounds everything else) but I'm guessing that didn't work.
More:
Googling suggests that variables cannot begin with a number. Is this what is stopping me here?
1. I've managed to show the temperature though, just not change it.
2. How do you get round that? I tried changing the code so that 'celsius' would give 'Temperature: 10C' rather than '10C' but that didn't solve it.
i assume the error is in the line var temp = $("#temperature").html;
Does it help if you change it to var temp = $("#temperature").html();?
html is a jQuery function, so you need to call it with the parantheses. Otherwise temp will not contain the content of the #temp element, but rather a reference to the html method. Therefore you don't get the last letter of the content.

Can't access JavaScript variable inside function

I'm making an extension for selected text search in different search engines. One of the menu items changes if the selected string is a particular one. I have this done so far and it does what I want, except I can not make the "title" of the menu change. How do I give value to the variable "myTitle" in if statement inside the function?
Thanks in advance.
var myTitle; // if I give value here it does work, but I need the value based on the if statement bellow.
function myFunction(selectedText) {
if(selectedText.match (/someString|SomeOtherString/)) {
var myURL1 = 'https://someURL' + selectedText;
chrome.tabs.create({url: myURL1});
myTitle = "title1"; //I can not make the variable to get this value here
}else{
var myURL2 = 'https://someOtherURL' + selectedText;
chrome.tabs.create({url: topicCall});
myTitle = "title2"; //I can not make the variable to get this value here
}
}
chrome.contextMenus.create({
**"title": myTitle,** // this should change based on the selection
contexts:["selection"],
onclick: function (info)myFunction(info.selectionText);}
});
You have "cause and effect" mixed up. When chrome.contextMenus.create is called, myFunction has not executed yet and the value of myTitle has not been assigned.
Perhaps, you can use chrome.contextMenus.update, after the page is loaded. You could create the menu, with default titles, but with unique IDs. Then use the above method, based on whatever the "selectedText" is, and use the IDs to replace the titles.

Accessing Images from an array?

I need to create a function where the user can access input question , and they can see different results. It's a magic eight ball simulation. I need to use an array, but i'm not sure how to do this with images.
Here's what I have now.
function eightBall() {
var answer = document.getElementById('questBox').value;
answer = answer.toLowerCase();
if (answer.search(/[?]/) > -1) {
var no = '../images/eightBallNo.png';
$('#answerImages').html(no);
}
}
I'm not sure how to do this, so any help would be appreciated. In addition, I need to make it so that when the user enters the same question, it always returns the same result. My instructions were to do this through an if statement. Again, any help would be greatly appreciated.
Create a map using an object and store each question and the resulting random mage in it. When somebody asks a question, check to see if you've already mapped that question to something. If so, use the cached result. If not, get a random image from your array, and then add it to the cache:
// empty cache to use
var answerMap = {}
// array of your images
var images = ['image_1.png', 'image_2.png', ... 'image_n.png'];
function eightBall() {
var imageToUse = false;
var answer = document.getElementById('questBox').value;
answer = answer.toLowerCase();
// this syntax could be wrong, I forget the check as my JS is rusty
// check the cache to see if we got asked this before
if (answerMap[answer] != undefined) {
// if so, use the cached image value
imageToUse = answerMap[answer];
} else {
// otherwise, get a random image, and add it to the cache
var randomIndex = Math.floor(Math.random()*images.length);
imageToUse = images[randomIndex];
answerMap[answer] = imageToUse;
}
// do whatever you need to do with the image
}
Use that URL in an IMG tag, like this:
var no = '../images/eightBallNo.png';
$('#answerImages').html('<img src='+no+'/>');
But, this doesn't use an array. Where were you needing to use an Array? An Array of image urls?

Detect Once a Certain Word Has Just Been Entered in a Textarea

Considering features like EditArea's and CodeMirror's autocomplete, I was wondering if, like Dreamweaver, there is a way to detect if the last word you entered is in a certain list then provide the same kind of suggestion box but with the function's arguments. I imagine you would use a regular expression on the entire field or possibly split() the whole thing (or the current line) then use the length attribute of the array to find the last bit of text, then do something involving an indexOf-like operation; however, this seems like it would get a bit resource-intensive. It almost looks like I've answered my own question, but it always helps to fully explain one's quandary, especially publicly. There's gotta be a better solution than mine. I appreciate any input. Thank you.
Put the list of words to match in an object, have the text or options to display as the value. Then on keyup or keypress you can get the last word of the text area using a function like:
function showLastWord(id){
var el = document.getElementById(id);
var lastWord = el.value.match(/\w+$/);
return lastWord? lastWord[0] : '';
}
Then check if the word is in the list and do stuff appropriately.
Edit
A small example is:
<textarea onkeyup="showHelp(this);"></textarea>
<script>
var getLastWord = (function() {
re = /\w+$/;
return function (s){
var lastWord = s.match(re);
return lastWord? lastWord[0] : '';
}
}());
var keyWords = {foo:'foo was typed',bar:'bar was typed'};
function showHelp(el) {
var lastWord = getLastWord(el.value);
// Check for matching own property of keyWords
if (keyWords.hasOwnProperty(lastWord)) {
// Do stuff
console.log(keyWords[lastWord]);
}
}

how to capture the mouseover element?

i am developing an autocomplete feature.but i am facing one problem there...
when i click on the suggestion box one of the results will not enter into the suggest html box...
function handleOnMouseOver(oTr)
{
deselectAll();
oTr.className ="highlightrow";
position = oTr.id.substring(2, oTr.id.length);
updateKeywordValue(position);
}
can you plz tell the solution
thanks
function updateKeywordValue(oTr)
{
var oKeyword = document.getElementById("keyword");
var strKeyword="";
var crtLink = document.getElementById("a" +oTr.id.substring(2,oTr.id.length)).toString();
crtLink = crtLink.replace("-", "_");
crtLink = crtLink.substring(0, crtLink.length);
oKeyword.value=unescape(crtLink.substring(googleurl.length, crtLink.length));
strKeyword=oKeyword.value.toString();
if (oTr.id.substring(2,oTr.id.length)==0)
{
oKeyword.value=strKeyword.substring(3,strKeyword.length);
}
selectedKeyword=oKeyword.value;
}
you should get rid of the second parameter in the substring() method. Since you just want the remainder of the string, I'm guessing, that is the default if you don't set a second value.
position = oTr.id.substring(2);
My guess is that you are getting the value of the keyword from the id, and pushing that into the input box, right? If that's the case, we'll need to see more of your code. Specifically, I'd like to see the updateKeywordValue function and I'd also like to know if the text that they are hovering over is the text you are trying to send the input box. If so, you could probably simplify the whole thing and go with something like:
function handleOnMouseOver(oTr)
{
deselectAll();
oTr.className ="highlightrow";
keywordbox.value = oTr.innerHTML;
}
But this is based on the assumption that the only data inside the hovered row is the text, and no other html. And I had to make up a name for your input box.
But if this way off, this is because we need more information to see the real problem.

Categories