Unable to set selected attribute after page loads - javascript

My html page with SELECT and OPTIONS values sets one of the options as a default.
Were the user to choose a different option, which then takes him to a new page, I’d like to preserve that value so the next time home page is generated the value the user selected should remain on display, rather than the original default value, when the window reloads.
How do I do this in javascript?
I had tried to save values via a DOM capture of the selected value, but I don’t seem to be able to change that original default value.
E.g.,, one line of code reads:
window.location.reload();
yet were I to use “hold values” to capture the user’s selected option that differs from the default option, like so:
var holdPick = document.getElementById(“uPick”).value;
window.location.reload();
document.getElementById(“uPick”).value = holdPick;
that won’t do the trick, and I know not why.

When you reload a page, all the JavaScript is reloaded too. So, that's why the JavaScript snippet you posted doesn't seem to be working... The line after window.location.reload(); isn't even run at all. If you want to have a value that persists between page loads, you'll need to set and retrieve a cookie. Check out the JavaScript document.cookie API at MDN. That should tell you what you need to know about storing and retrieving your value in a cookie.

Why: every time var holdPick is executed it will create variable from scratch.
Second line tells the browser to reload page, so the third line never gets the chance to be executed.
I'd recommend usage of HTML5 Web Storage
if (sessionStorage.uPick) { //check if variable has been set already
document.getElementById(“uPick”).value = sessionStorage.uPick;
} else {
sessionStorage.clickcount = document.getElementById(“uPick”).value;
}
you can use cookies also, but I don't think it is as straight forward.

Related

Html Storage resets every refresh, initialize function not working

For a website I am working on, I am trying to keep information on how many items you buy to be shown across html pages. Researching how to do this has led me to believe that Html sessionStorage is the best way to do this (if there is a better/easier way please let me know). Yet, whenever I refresh the html page or go to another page the data resets.
Here is my code:
function initialize(name, val) {
if(localStorage.getItem(name) === null) {
localStorage.setItem(name, val);
}
}
initialize("subCost", 0);
initialize("quantity", 0);
initialize("hasProduct", false);
Then since the storage only stores strings, I convert these into integers and boolean
var $quantity = parseInt(localStorage.quantity);
var $subCost = parseInt(localStorage.subCost);
var $hasProduct = localStorage.hasProduct == "true";
Before without the initialize function, I made the local storages items like this
localStorage.setItem("subCost", 0);
localStorage.setItem("quantity", 0);
localStorage.setItem("hasProduct", false);
and still converted these into those variable but they never saved with each refresh. How do I get these to save changes I make to them with each refresh.
The .setItem() method on localStorage doesn't only "sets" a "memory placeholder" for a value... It also overwrites it, if it already exist.
To save the user generated values, the best "moment" to save a "change" is the change event.
Use the same .setItem() method as in your initialize() function.
$("input").on("change",function(){
// Get id and value.
var id = $(this).attr("id");
var value = $(this).val();
// Save!
localStorage.setItem(id,value);
});
CodePen
Just as a hint...
This method to save values locally is ephemeral...
Values are kept until user closes the browser.
Not just closing the page, but closing the browser completely.
So to keep some values between pages navigated, this is the optimal use.
To store values for a longer run (like 6 months or longer), use cookies.
Have a look at jQuery Cookie plugin.

Attempting to use a global array inside of a JS file shared between 2 HTML files and failing

So I have one HTML page which consists of a bunch of form elements for the user to fill out. I push all the selections that the user makes into one global variable, allTheData[] inside my only Javascript file.
Then I have a 2nd HTML page which loads in after a user clicks a button. This HTML page is supposed to take some of the data inside the allTheData array and display it. I am calling the function to display allTheData by using:
window.onload = function () {
if (window.location.href.indexOf('Two') > -1) {
carousel();
}
}
function carousel() {
console.log("oh");
alert(allTheData.toString());
}
However, I am finding that nothing gets displayed in my 2nd HTML page and the allTheData array appears to be empty despite it getting it filled out previously in the 1st HTML page. I am pretty confident that I am correctly pushing data into the allTheData array because when I use alert(allTheData.toString()) while i'm still inside my 1st HTML page, all the data gets displayed.
I think there's something happening during my transition from the 1st to 2nd HTML page that causes the allTheData array to empty or something but I am not sure what it is. Please help a newbie out!
Web Storage: This sounds like a job for the window.sessionStorage object, which along with its cousin window.localStorage allows data-as-strings to be saved in the users browser for use across pages on the same domain.
However, keep in mind that they are both Cookie-like features and therefore their effectiveness depends on the user's Cookie preference for each domain.
A simple condition will determine if the web storage option is available, like so...
if (window.sessionStorage) {
// continue with app ...
} else {
// inform user about web storage
// and ask them to accept Cookies
// before reloading the page (or whatever)
}
Saving to and retrieving from web storage requires conversion to-and-from String data types, usually via JSON methods like so...
// save to...
var array = ['item0', 'item1', 2, 3, 'IV'];
sessionStorage.myApp = JSON.stringify(array);
// retrieve from...
var array = JSON.parse(sessionStorage.myApp);
There are more specific methods available than these. Further details and compatibility tables etc in Using the Web Storage API # MDN.
Hope that helps. :)

Keeping a user-defined JScript variable after reload?

In my HTML document, a button is displayed, and it's onclick event is to alert the variable countervar. Another button can be used to bring countervar up using countervar++. Countervar is never defined in the JScript document, because I want countervar to stay how it was last defined by a user. Like I expected, countervar was nil after each reload. Saving browser cookies also would not work, because the same variable has to be displayed to each user who views the document. I'm looking into "global variables" for an answer, but no luck. Help?
As suggested in the comments, you can use localStorage to achieve part of what you want:
var counter;
// save to local storage
window.localStorage.setItem("counter", counter);
// you can call this whenever you make changes to the counter variable
// load from local storage
// call it when the page loads
if( window.localStorage.getItem("counter") === null){
counter = 0;
}
else{
counter = parseInt(localStorage.getItem("counter"));
}
This will allow you to save the variable for one user. If you want to share it between users, it can't be done just using client side scripting. You'll have to have some sort of server storage/database.

onclick: do something after changing location

Suppose I want to do the following: when clicking a 'div', change to another location (as if it was ...) and then do something. I have tried with this code:
<div onclick="location.reload();location.href='...';togglebox('#ident')">Title</div>
where ident is the identifier of an object in the new location href='...' and togglebox is a function defined in the script. But it seems that the browser tries to accomplish togglebox('#ident') before changing the location, so the output is not the expected one. For instance, if I try
<div onclick="location.reload();location.href='...';console.log(5)">Title</div>
then a 5 appears instantaneously before changing the location, while I expect the browser first changing the location and then showing 5.
Is there any solution to this reversal-order solution?
Any suggestion is welcome
One way would be to use a query string to tell the destination page what to do. However, if you want a hack that will do almost exactly what you ask, you can do this:
(This goes in your current page's click event handler)
window.location.href = '...'; // Go to another page in your site
localStorage.setItem('exec',"yourCodeInQuotes()");
Now the destination page should either be prepared to handle the ident you mentioned from localStorage or just evaluate the code directly. Either way you need the destination page to anticipate the data that's coming.
(This goes in the destination page)
var message = localStorage.getItem('exec'); // Will get whatever you stored
eval(message); // Will attempt to run it as JavaScript
$('#'+message); // Or find it if it was your ident and do stuff...

Send variable value from page to another page

In my case :
I have created a form and in the form there is a button and a combo box that contains the data (Say it page A). When I click on the button, all I wanted was to call page B to perform a second process. The syntax for calling the page B is :
bb.pushScreen('PageB.htm', 'PageB', {'Key': MyComboValue});
How do I after page after page B called B will capture and get the value of the "MyComboValue" being sent from page A ??
Regards,
Bertho
Firstly, this is available in bbUI 0.94 (next branch) just to make sure you're running the right build.
Now, the object you pass to the new page is available in the ondomready, and onscreenready functions, so you would do something like this:
onscreenready: function(element, id, passed_object) { }
There are several ways to achieve this:
Use cookies to save the data. Wouldn't recommend it much.
Use localStorage. Works for newer browsers, some browsers won't be able to enjoy it.
Pass the values as querystring parameters when doing the change of url.
I would go with the third option myself. If you're only using JavaScript and you're not using any server side programming language:
Attach an event to the button so that when clicked, it fetches the data and generates a querystring. Then: top.location = "http://something/PageB.htm?" + querystring;
On the Page B, read the querystring (top.location.href) and parse it to get the querystring. Use the values of the querystring to set whatever you want on your page.
If you require code or if I misunderstood, please tell and I will check right away!
EDIT: I just realized you tagged your question as using blackberry-webworks. I have never worked with it and thus I have no idea if my solutions make sense on it. Try to specify it on your question too if possible, or in the title :)

Categories

Resources