Remember and pass value by clicking back button - javascript

I am using MyApp.updateHashLabel on using browser location hash to enable back/forward events which works with only one issue - it doesn't pass value. This is my html code and one of the buttons (fourth) has got onClick MyApp.updateApp with extra value which I want to pass when I click on a back button from another screen/state. So when I am clicking on second button after fourth and go back it shows my a correct screen but doesn't display the value = 6. Is there any way to put it in sessionStorage for this action? Or there may be a different solution...
<div class="button-bar">
<button onclick="MyApp.updateApp(1, true);" type="button">ONE</button>
<button onclick="MyApp.updateApp(2, true);" type="button">TWO</button>
<button onclick="MyApp.updateApp(3, true);" type="button">THREE</button>
<button onclick="MyApp.updateApp(4, true, 6);" type="button">FOUR</button>
</div>
<div id="hash-label">#</div>
<div id="value-label"></div>
<div id="image-placeholder"></div>
This is my jQuery code:
MyApp.updateApp = function (hashValue, allowAppToUpdateHash, valueID) {
var index = parseInt(hashValue, 10);
var imageNode = document.getElementById('image-placeholder');
var id = parseInt(valueID, 10);
}
And the function of a value usage is:
window.article = function (id) {
$("#value-label").html(id);
}
Please see my whole code on jsfiddle here: http://jsfiddle.net/nzsqt06a/1/
Really appreciate your help.

you could intercept the args and store them in session storage, and recover them once the DOM is loaded again.

Related

How can I use cookies in JavaScript to set true or false data to close a popup permanently?

I was wondering if it was possible to use cookies in JavaScript to close a popup for cookie usage.
Is there any way to do it?
The code below sticks both of the pieces of code together as one entity, so it deletes both parts, while only trying to delete the popup part of it. I need to keep the <div id="e">© 2022 dont worry</div> part. Is there also a way to fix both issues at the same time or is that not possible?
My code:
<div id="sticky" class="alert-cookies">By using this search engine, you accept our use of cookies.Information
<href style="width: 100%">
<input id='btn' type="submit" onclick = "deleter()" value='OK'>
<script>
function deleter() {
document.cookie = true;
var btn = document.getElementById('btn');
btn.onclick = function () {
document.getElementById('sticky').remove();
this.remove();
};;
}
<div class="after footer_side1_wrapper">
<div id="e">© 2022 dont worry</div>
</div>

Use form data to update web page

Before I provide a bunch of code I'd like to first find out if what I'm trying to do is even possible.
I've created a web based version of the dice game called PIG using HTML & JavaScript. The user can change some of the game's settings by clicking on a "Settings" button on the main page. This button brings up a modal window containing an HTML form (). I'd like to use the data that the users enters and submits on this form to update various settings on the game's main page.
I chose to use an HTML5 form because was hoping to use the native HTML5 form validation capabilities rather than try and replicate that validation checking logic myself using JavaScript.
So my approach was to use javascript to get the data off the form on submit. I tried two different approaches to get this to work:
1) Using an "onsubmit=function getSettings()" on the tag
2) Using a submit button for the form with an onclick="getSettings()".
With both of these approaches I was able to successfully get all the values from the form on submit and use those values to successfully populate the main game page using the gettSettings() function however when I exit the getSettings() function the webpage values that I updated don't stick...they revert back to the original values regardless of which of these two approaches I use.
I know the values were successfully updated because when I set a break point on the last statement of the getSettings() method I can see that all of the values on the main page have been updated to reflect what was filled in on the form...so I know I'm grabbing all of the data successfully and updating the main page with those values.
I'm puzzled as to why the values that I successfully change on the web page simply revert back to their original value upon exit of the getSettings() function.
Maybe it's just not possible to do what I'm trying to do? And if not does anyone know why given I can see the values are successfully changed before they revert back to their original value. What am I missing?
Again I'm using a Form and collecting the data on submit so that I can leverage the "native" HTML5 form validation capabilities.
Regards.
***** EDIT TO ADD KEY SEGMENTS OF CODE *******
Here is the code HTML Code for the modal form:
<form name="config-settings" onsubmit="getSettings()">
<!-- <form name="config-settings">-->
<span class="errMsg"></span>
<div class="row clearfix">
<div>
<label>Player 1:</label>
</div>
<div>
<input type="text" name="input-name-0" id="input-name-0" maxlength="10" placeholder="Enter name" pattern="^\S+$">
</div>
</div>
<div class="row clearfix">
<div>
<label>Player 2:</label>
</div>
<div>
<input type="text" name="input-name-1" id="input-name-1" maxlength="6" placeholder="Enter name" pattern="^\S+$">
</div>
</div>
<div class="row clearfix">
<div>
<label>Winning Score:</label>
</div>
<div>
<input type="number" name="winning-score" id="winning-score" default="100" placeholder="Enter winning score">
</div>
</div>
<div class="row clearfix">
<div>
<label>Number of Dice:</label>
</div>
<div>
<select name="diceValues" id="dice-value">
<option value=""> - Select - </option>
<option value="dice-1">One Dice</option>
<option value="dice-2">Two Dice</option>
</select>
</div>
</div>
<!-- Below is alt method I used to submit form..yields same results -->
<!-- <input type="submit" value="Submit" onclick="getSettings()">-->
<input type="submit" value="Submit">
</form>
Here are the global variables defined and used in getSettings() method:
// Global variables
var scores, roundScore, activePlayer, gamePlaying, gamesWonCount, playerNames, winningScore, numOfDice, matchScore, msgs;
var player0, player1, score;
var player0Field = document.getElementById('name-0');
var player1Field = document.getElementById('name-1');
var scoreField = document.getElementById('winScore');
Here is the listener for the Settings button on the main web page that brings up the setting modal window containing the settings form:
//*********************************************************
// Open Settings Modal Windows
//*********************************************************
document.querySelector('.btn-settings').addEventListener('click', function () {
// Settings can't be changed if game is actively underway
if (!gamePlaying || roundScore === 0) {
document.querySelector('#modal-settings').style.display = 'block';
} else {
// Make error message visible
msgs.style = 'block';
// Create message to indicate settings successfully updated
msgs.textContent = "Settings can't be updated during game";
msgs.style.backgroundColor = 'pink';
fadeOut(msgs);
}
});
Here is the getSettings() javaScript function (note: there are no local variables defined in this function...they are all defined as global values (first few lines of javaScript app).
function getSettings() {
// Alternative call if I want this function to be called via eventListner
//document.querySelector('.btn-save').addEventListener('click', function () {
console.log("getSettings method called");
player0 = document.forms["config-settings"]["input-name-0"].value;
player1 = document.forms["config-settings"]["input-name-1"].value;
score = document.forms["config-settings"]["winning-score"].value;
// Reset msgs so they will be displayed each time
msgs.style = 'block';
playerNames[0] = player0;
player0Field.innerHTML = playerNames[0];
playerNames[1] = player1;
player1Field.textContent = playerNames[1];
// Set Winning score on UI to value on form
scoreField.textContent = score;
// numOfDice = document.getElementById('dice-value').value;
// Create message to indicate settings successfully updated
msgs.textContent = "Successfully updated settings";
msgs.style.backgroundColor = 'lightgreen';
fadeOut(msgs);
document.querySelector('#modal-settings').style.display = 'none';
}
I don't know exactly what this getSettings() function of yours is supposed to do, but I can try to give you a piece of advice:
Some of the form validation capabilities of HTML5 are not entirely supported on all of the used browsers(some users don't fancy to update their browser). Therefore relying on the "native" validation of HTML5 isn't exactly best practice.
If you want to manipulate the form values in any way before submitting the form I would rather add a listener to the submit button for click events, prevent any other action, make the checks/ manipulation of the form data and then manually submit the form. Anyways, front-end validation isn't entirely safe, so if you're peddling sensitive data it's mandatory that you'll make checks on serverside(if your app uses a server).
To exemplify what I've explained earlier:
document.getElementById("myBtn").addEventListener("click", function(event){
//Stops the form submitting.
event.stopImmediatePropagation();
//Do the checks here.
//Sends the form.
document.getelementById("myForm").sumbit();
);
If you change local variables inside this getSettings() function, the variables will be changed only within the function scope. You might want to read about scope in javascript. (this was just an educated guess).
I hope you find this useful, good luck!
Okay...I finally figured it out! The problem was not a scoping problem but instead and issue with how "onSubmit" works.
The solution involved making two changes:
1) Adding a return statement to the "onsubmit" attribute when calling the "getSettings()" function;
<form name="config-settings" onsubmit="return getSettings()">
2) Returning false at the end of the gettSettings();
return false;
Note: I had previously tried returning true but not false. I was errantly under the impression that returning false value from getSettings() function would disable HTML5 "native" validation and force me to implement all of the error checking myself...which was not what I wanted. It is now my understanding that returning false merely prevents the form from being submitted..but it doesn't disable the HTML5 native validations.
This solution worked perfectly for me because my goal was not to submit the form to the server (as there is no server component here) but merely to use the "native" HTML5 form checking and then update the values on the local web page.
With all of that said I'm still not entirely sure why when I didn't provide the return statement or when I returned true why all of my changes reverted back to their originally value. If anyone can shed some light on why I'd appreciate it.
Cheers

store 2 websites in 1 file and dynamically change between them

so this is a very vague question but say I had a single .html file and I wanted to store essentially 2 websites in the one file and swap to the 2nd page when a condition became true on the first page(preferably a onclick javascript event) kind of like an if statement(if condition A becomes true on page one: show page 2 else: continue to show page 1) would this be possible in just javascript or would I need the aid of other programming languages and what would be the most optimum way of going about this? I would want the data entered in an input feild on page 1 also available on page 2.
sorry for vague question and horrible formatting, this is my first ever question.
Joel, I don't have enough reputation to comment and so I must type an answer.
Local storage allows you to store a value (page number to display) within the user's local browser memory. This value can be tested for existence (useful for true/false conditions) and can be read (for meaningful values).
All you need to do is bind the creation of a simple local storage object (the page number to display). Bind the code to create the storage object to whichever event you want (such as a button click).
localStorage.setItem('entryPage', '2');
You will also need some code to read within the HTML file to decide what to display (via scroll, hidden and displayed DIV elements or whatever technique you are using).
if(localStorage.getItem('entryPage')) {
//show page two code
}
Check here for a full tutorial set:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
Below is a chrome-tested one-page solution just demonstrating the concept of the local storage part. You'll always be within the same HTML file, but load will show content one until you click the button and set local storage to display page 2, then any future load will be page two until you clear local storage.
<!DOCTYPE html>
<html>
<body>
<div id="main-container">
<div id="content-one" style="display:block;">
<p>This is page one content</p>
<button id="showTwo">Show Page 2</button>
</div>
<div id="content-two" style="display:none">
<p>this is content for page 2</div>
</div>
</div>
<script>
//this function actually swaps display
function swapper(){
document.getElementById('content-one').style.display = 'none';
document.getElementById('content-two').style.display = 'block';
}
//if the value exists in storage, swap them
if(localStorage.getItem('entryPage')) {
swapper();
}
//when button clicked, swap them and store value
var btn = document.getElementById("showTwo");
btn.addEventListener("click", function(){swapper();localStorage.setItem('entryPage', '2');}, false);
</script>
</body>
</html>
To clear local storage on Chrome, see LOCAL AND SESSION section here:
https://developer.chrome.com/devtools/docs/resource-panel#local-and-session-storage
And below is a version including a text-box which simply used the value of the local storage object to hold the data you wish to carry to content page 2. (Remember, if you have tested the first example above you must clear local storage to use this example below because otherwise it will never show you the first content pane).
<!DOCTYPE html>
<html>
<body>
<div id="main-container">
<div id="content-one" style="display:block;">
<p>This is page one content</p>
<input type="text" id="theInput"></input>
<button id="showTwo">Show Page 2</button>
</div>
<div id="content-two" style="display:none">
<p>this is content for page 2</div>
<p id="theOutput"></p>
</div>
</div>
<script>
//this function actually swaps display and shows the value from page 1 textbox
function swapper(theValue){
document.getElementById('content-one').style.display = 'none';
document.getElementById('content-two').style.display = 'block';
document.getElementById('theOutput').innerText = theValue;
}
//if the value exists in storage, swap them and pass on the value of textbox
if(localStorage.getItem('entryPage')) {
swapper(localStorage.getItem('entryPage'));
}
//when button clicked, swap them and store value
var btn = document.getElementById("showTwo");
btn.addEventListener("click", function(){
var theData = document.getElementById("theInput").value;
swapper();
localStorage.setItem('entryPage', theData);
}, false);
</script>
</body>
</html>

Oracle Openscript and Javascript (AngularJS)

I'm using Openscript on a form page that is using a clickable div "save" button. When the button is clicked manually a javascript event is executed to save the changes on the page. When I play back the script, the script clicks on the button and gets redirected to the next page but does not save the changes I made on the text boxes. I'm guessing it doesnt run the ng-click updateUser() function when doing a playback. How can I get openscript to click on the save button and run the javascript function?
Openscript code:
web.button(
"/web:window[#index='0' or #title=Payment Processor']/web:document[#index='0']/web:form[#name='form' or #index='0']/web:button[#index='1']")
.click();
This is what the div save button code looks like:
<div class="row">
<div class="col-xs-12">
<button class="btn btn-primary" ng-click="updateUser()">
<i class="fa fa-asterisk"></i>
Save
</button>
</div>
</div>
.click(); should work, but you can try mouseClick() too.
Using OATS 12.4.0.1 and testing against the AnjularJS Docs example #64, I playback this similar ng-click to increment the displayed count. My example below shows with mouseClick()
AnjularJS example #64:
<body ng-app="">
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
<span>
count: {{count}}
</span>
</body>
Openscript code:
web.window(2, "/web:window[#index='0']").navigate(
"https://docs.angularjs.org/examples/example-example64/index.html");
{
think(14.929);
}
web.button(4, "/web:window[#index='0']"
+ "/web:document[#index='0']/web:button[#index='0']")
.mouseClick(null, 1, false);
// .click(); // this should work too.
In OpenScript there is an option to call the JavaScript function directly.
String javaScript = "updateUser()";
DOMDocument doc = web.document("/web:window[#index='0' or #title=Payment Processor']/web:document[#index='0']/web:form[#name='form' or #index='0']");
doc.executeJavaScript(javaScript);
You can use the above code to call the JavaScript function.
So far I never faced this issue that form is not getting saved or any other click is not saved..
just try following steps..
Record one more time a new script with save option
add proper think time
think(8); or some time I even do think(8);think(8); as some places openscript does not record any think time.
Actually I always increase think time after every step as uniform time
think(8); after every single step even if some think time is there, add more and if no think time add some. The maximum is think(10);.

Submit button displays an image based on the time of the day

Basically there is an empty box with a submit button directly underneath. The empty box might have a default picture loaded to begin with. When a user clicks the submit button, how can I display a different picture (in place of the default) based on a certain time of the day. I don't really need an answer regarding the checkTime logic, but I would appreciate some help with regards to the submit button being able to change a picture in the same spot. Thanks guys.
if you just have a simple button, you can add an onclick event to it:
Example 1:
<input type="button" onclick="changeImage()" />
and your changeImage() function will have the logic to follow
Example 2:
<input type="button" id="submitButton" value="Button"/>
Javascript -
document.getElementById("submitButton").onclick = function () {
// run the logic
}
images can be switched using the src property
javascript -
document.getElementById("theImage").src = "newImage.jpg";
Since you are talking about a "Submit" button I assume it is within a form. Is submitting the form supposed to have some other effect? If not, use type="button" rather than type="submit". Either way, here is some basic code to get you started:
<img id="thePicture" src="...">
<input type="submit" value="Go" onclick="return changePicture();">
<script>
function changePicture() {
// your logic here to set which picture to use
var newPicture = "yourpath/images/img1.jpg";
document.getElementById("thePicture").src = newPicture;
// return false to stop the form submitting, otherwise
return true;
}
</script>

Categories

Resources