Increment variable value of a variable on webpage refresh - javascript

I have code which just increments a value by 10 on every button click. I want that code to increment the value whenever I refresh the page. How do I do that?
Here is the code:
<html>
<head>
<script type="text/javascript">
function reveal() {
var val = document.getElementById("outputtext").value;
var result = parseInt(val) + parseInt(10);
document.getElementById("outputtext").value = result;
}
</script>
</head>
<body>
<p> <h3>Click on below button to increase the value by 10<h3> </p>
<button onclick="reveal()"> Increment</button>
<table>
<tr>
<td><textarea id="outputtext">10</textarea></td>
</tr></table>
</body>
</html>

For the title of your question, you might use the following Javascript function to bring up the previous page:
history.back();
as stated in this question on SO: How to emulate browser back button using javascript
If you want to increment a variable on page refresh with Javascript, you should save this variable as a cookie on the users browser:
document.cookie="increment=10";
Either of these links might help you with this: http://www.w3schools.com/js/js_cookies.asp http://www.htmlgoodies.com/beyond/javascript/article.php/3470821

You could do this without cookies, by using a hash (#value) in the URL. Try this code :
<html>
<head>
</head>
<body>
<h3>Click on below button to increase the value by 10<h3>
<button onclick="reveal()"> Increment</button>
<table>
<tr><td><textarea id="outputtext">10</textarea></td></tr>
</table>
<script type="text/javascript">
//Get the last value
var current = parseInt(location.hash.slice(1));
//If it is set, increment it
if(current){
document.getElementById("outputtext").value = current + 10;
location.hash = '#' + (current+10);
}
function reveal() {
var val = document.getElementById("outputtext").value;
var result = parseInt(val) + parseInt(10);
document.getElementById("outputtext").value = result;
//Set the value
location.hash = '#' + result;
}
</script>
</body>
</html>
Note that I moved the javascript to the end of the file, so that #outputtext is already defined when the code gets executed.

Related

Set to true state a checkbox in a different page(javascript)

Here's the Script.
javascript
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
$('#website-design').attr('checked',true);
window.location.href = "/contact";
}
}
}
I want to check my checkboxes when I click the button with an id=website-design-check.
Here is my HTML.
first.html
<a href="/contact" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
Here's the second HTML file where checkbox is.
second.html
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
Now how can I achieve what I want base on the description given above. Can anyone help me out guys please. I'm stuck here for an hour. I can't get any reference about getting a checkbox state from another page.
To do this, you can modify your button link and add in additional parameters that you can then process on the next page.
The code for the different pages would be like:
Edit: I changed it to jQuery, it should work now.
Script
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
window.location.href = "second.html?chk=1";
}
}
second page
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script type="text/javascript">
var url = window.location.href.split("?");
if(url[1].toLowerCase().includes("chk=1")){
$('#website-design').attr('checked',true);
}
</script>
since your checkbox is in another html page, so it's totally normal that you can't get access to it from your first html page!
what I can offer u is using the localstorage to keep the id and then use it in your second page to check if it's the ID that u want or not.
so change your function to this :
function linkPageContact(clicked_id){
localStorage.setItem("chkId", "clicked_id");
window.location.href = "/contact";
}
then in your second page in page load event do this :
$(document).ready(function() {
var chkid = localStorage.getItem("chkId");
if(chkid === 'website-design-check'){
$('#website-design').attr('checked',true);
});
You can't handle to other sites via JavaScript or jQuery directly. But there's another way. You can use the GET method to achive this.
First you need to add to the link an attribute like this in your first.html:
/contact?checkbox=true
You can change the link as you want with JavaScript.
Now it will refer to the same page but it can be now different. After that you can receive the parameter with this function on the second.html.
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
I got it from this post thanks to Bakudan.
EDIT:
So here is an short theory.
When the user clicks the button on the first page, then you change the link from /contact to /contact?checkbox=true. When the user get forwarded to second.html then you change the checkbox depending on the value, which you got from the function findGetParameter('checkbox').
As all have mentioned you need to use session/query string to pass any variable/values to another page.
One click of the first button [first page] add query string parameter - http://example.com?chkboxClicked=true
<a href="secondpage.html?chkboxClicked=true>
<button>test button</button>
</a>
In the second page- check for the query string value, if present make the checkbox property to true.
In second page-
$(document).ready(function(){
if(window.location.href.contains('chkboxClicked=true')
{
$('#idOfCheckbox').prop('checked','checked');
}
})
Add it and try, it will work.
Communicating from one html file to another html file
You can solve these issue in different approaches
using localStorage
using the query parameters
Database or session to hold the data.
In your case if your application is not supporting IE lower versions localStorage will be the simple and best solution.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<a href="contact.html" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
<script>
function linkPageContact(clicked_id) {
localStorage.setItem("chkId", clicked_id);
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script>
$(document).ready(function () {
var chkid = localStorage.getItem("chkId");
if (chkid === 'website-design-check') {
$('#website-design').attr('checked', true);
}
});
</script>
</body>
</html>

Displaying input back to a user - javascript

I have found several questions with answers on how to do this, but I think my problem is an interesting one. I am trying to have a user enter in their name in a text box, then once they hit a button it will display it back to them.
This is the code I have:
<html>
<head>
<title>Side Bar test</title>
<link rel="stylesheet" href="test.css" />
</head>
<body>
<div id="sideWrapper">
<p id="wrapper"><label for="name">Name: <input type="text" name="name" id="name"></p>
<button onclick="display();">Submit</button>
</br>
<div id="playerName">
</div>
</div>
</body>
<script type="text/javascript" language="javascript">
var input = document.getElementById("name").value;
function display() {
document.getElementById("playerName").innerHTML = "<p>Player: " + input + "</p>";
}
</script>
When the document.getElementById("name").value is called, it only takes whatever was in the text field when the page first loaded. Trying to update it after and clicking the button doesn't work. So, if you type "John Doe" in the field and then reload the page and hit the button, it will display John Doe. But if you try to change it, it doesn't work. I have tried moving the script to the <head> but that only makes it undefined.
How can I make it so the display() function sees what the user types in the box and updates it to print it out to the screen?
EDIT: Fixed the code by moving the input line into the function body.
<script type="text/javascript" language="javascript">
function display() {
var input = document.getElementById("name").value;
document.getElementById("PlayerName").innerHTML = "<p>Player: " + input + "</p>";
}
</script>
You need to put your declaration of input inside your display function.
function display() {
var input = document.getElementById("name").value;
document.getElementById("playerName").innerHTML = "<p>Player: " + input + "</p>";
}
As you currently have it, the value of input is stored when the page is loaded, so it does not update automatically.
You're problem is that this: var input = document.getElementById("name").value;
fires immediately when the program loads.
To fix this, do this:
function display() {
var input = document.getElementById("name").value;
document.getElementById("playerName").innerHTML = "<p>Player: " + input + "</p>";
}
That way, the input variable is assigned the current value of the input element each time the function is called.
Here is a fiddle to show that the input variable assignment fires when the page is loading. I added a default value to the input to show that no matter what you change it to afterwards, the value is always what the default is.
The input = document.getElementById("name").value; should be inside the function display(), because you will always set it it's initial value (empty).

Saving var using JavaScript and redirecting to URL

I have a very simple web form containing two input fields and a submit button.
What I would like to do is save the two strings inserted and redirect to my other HTML file (which is in the same folder).
HTML:
<!DOCTYPE html>
<html>
<title>Players enter</title>
<head>
<script type="text/javascript" src="ticTac.js"></script>
<link rel="stylesheet" type="text/css" href=styleSheet.css></link>
</head>
<body>
<form >
player one name: <input type="text" id="firstname"><br>
player two name: <input type="text" id="secondname"><br>
<input type="submit" onclick="checkNames();"/>
</form>
</body>
</html>
JavaScript:
function checkNames(){
var nameOne = document.getElementById("firstname").value;
var nameTwo = document.getElementById("secondname").value;
//window.location.href = 'C:\Users\x\Desktop\hw3\tic\Game.html';
//window.location.replace("C:\Users\x\Desktop\hw3\tic\Game.html");
window.location.assign("C:\Users\x\Desktop\hw3\tic\Game.html");
}
I have commented the two other options I tried which also do not work.
You are using an HTML form... this means that your submit button will fire and try to submit your form.
In order to prevent this, you need to prevent that event from triggering. A simple modification to your JavaScript function should do the trick.
function checkNames() {
event.preventDefault();
var nameOne = document.getElementById("firstname").value;
var nameTwo = document.getElementById("secondname").value;
window.location.href = 'SOME-PATH/Game.html';
}
To redirect to a page in your computer you can use:
window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html';
There are more than one way of passing the values to another page. Here is an example using query string.
In the page that has the values.
var q = '?nameOne=' + encodeURI(nameOne) + '&nameTwo=' + encodeURI(nameTwo)
window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html' + q;
In the page receiving the values.
var nameOne = location.search.slice(1).split("&")[0].split("=")[1];
var nameTwo = location.search.slice(1).split("&")[1].split("=")[1];
Use
window.location="url";

Undefined when doing document.write() with button OnClick="counter"

I'm new to programming and would need some help, why the document.write() didn't work and basically the page crashes... Can anyone help me?
<!DOCTYPE html>
<html>
<head>
</head>
<script type="text/javascript">
function showText() {
var x;
var counter;
if ( x === 0) {
counter = 0;
x = 1;
}
counter = counter + 1;
document.write("Times clicked: " + counter);
}
</script>
<body>
<script type="text/javascript">
showText();
</script>
<button onclick="showText();">Click Me!<button>
</body>
</html>
Avoid using document.write
Quoting from the MDN Developer Network documentation page:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document.
So basically, your issue is using document.write after the page has loaded: this will result in deleting the entire content of the page and displaying that string.
Also, your code doesn't work because your count variable is declared inside the showText function, and you're trying to access it outside of it, running into an error.
Solution
To make your code work you should create another element, let's say a <p> element, and display the text inside of it. Here's an example of a correct page:
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="btn">Click me!</button>
<p id="txt">Times clicked: 0</p>
<script type="text/javascript">
function showText() {
count++;
text.textContent = "Times clicked: " + count;
}
var count = 0,
button = document.getElementById("btn"),
text = document.getElementById("txt");
button.addEventListener("click", showText);
</script>
</body>
</html>
Check out a live demo here.

JS Variable Passing Via URL

I am designing a webpage that loads images of a document into the webpage and then will relocate to a specific image (page) based on a variable passed from another page. The code is below. Right now, it does not look like the variable 'page' is being updated. The page will alert
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<!-- Javascripts -->
<script type="text/javascript">
var pageCount = 40; /*Total number of pages */
var p; /*Variable passed to go to a specific page*/
function pageLoad(){ /*Loads in the pages as images */
for( i = 1; i<= pageCount; i++){
if(i < 10){
i = "0"+i;
}
document.body.innerHTML += "<div class='page'><a id='page" + i +"'><img src='pages/PI_Page_"+ i +".png' /></a></div>";
if( i == pageCount){
gotoPage(p);
}
}
}
function gotoPage(pageNum){ /* Moves webpage to target page of the PI */
window.location = ("#page" + pageNum);
alert(p);
}
function Test(){
window.open("./PI.html?p=15","new_pop");
}
</script>
</head>
<body onload="pageLoad()">
<div class="ExtBtn" onClick="Test()">
<img alt="Exit" src="design/exit_btn-02.png" />
</div>
</body>
</html>
The function TEST() was set up to allow me to have a link to re-open the page with p set to 15. The page opens, however, the function gotoPage() still alerts that p is undefined. Any ideas why that is?
Variables passed in the URL do not automatically become variables in JavaScript. You need to parse document.location and extract the value yourself.
p is never set a value anywhere so of course it will be undefined. You need to pull the value from the query string manually, JavaScript does not magically get the query string value for you.
Use the function here: How can I get query string values in JavaScript? to get the value.
Also why are you checking for the last index, set the go to call after the for loop.
Here is your code with the correct alert(p) working:
http://js.do/rsiqueira/read-param?p=15
I added a "function get_url_param" to parse url and read the value of "?p=15".

Categories

Resources