View Full Version : adding 1 to a variable
cat_evilness
11-22-2002, 03:45 PM
Hey guys I need some help.
Now I need code that will do this:
There will be a variable let's call it hunger and it will be a number let's say 0.
Now I want it so that when the user pushes a button it will add 1 to this number thus making the
0 into 1 and the 1 into 2 and so on. Oh and I also want to display this number :D
Can anybody help me?
Thankyou
Cat
ShriekForth
11-22-2002, 04:01 PM
Like this?
<script>
function addOne(fld){
document.temp.elements[fld].value = parseInt(document.temp.elements[fld].value) + 1;
}
</script>
<form name="temp">
<input type="text" name="total" value="0">
<br>
<input type="button" value="+1" onClick="addOne('total');">
</form>
You could also store the total in a variable, then you would not have to parse it out of the input field.
ShriekForth
beetle
11-22-2002, 04:27 PM
Well, you're being pretty vague...but the process for incrementing a variable is pretty simple.<script>
var hunger = 0;
function handleClick() {
hunger++;
document.getElementById('output').innerText = hunger;
}
</script>
<input type="button" value="Add to Hunger" onclick="handleClick()" /><br />
<span id="output">0</span>Of course, this just one of many possibilities, but without more specifics, I'm not sure what you need.
cat_evilness
11-22-2002, 06:08 PM
Thankyou guys those codes are great!!
To adapt from that is there anyway that you could still do that if the variable was in a different page from the button?
RadarBob
11-24-2002, 04:12 AM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>Adding One</title>
<meta name="generator" content="BBEdit 7.0">
<script type="text/javascript">
var theNumber = 0;
function addOne() {
document.addingNumbers.myNumber.value = theNumber++;
}
</script>
</head>
<body>
<form name="addingNumbers">
<input type="text" name="myNumber" value ="0" disabled="true">
<br>
<input type="button" value=" Add One " onclick="addOne();">
</form>
</body>
</html>
glenngv
11-25-2002, 07:03 AM
Originally posted by cat_evilness
Thankyou guys those codes are great!!
To adapt from that is there anyway that you could still do that if the variable was in a different page from the button?
you mean the variable is in a different frame?
using beetle's code:
<script>
function handleClick() {
objFrame = top.frames["FrameNameHere"];
if (objFrame && typeof objFrame.hunger!="undefined")
document.getElementById('output').innerHTML = ++objFrame.hunger;
else
document.getElementById('output').innerHTML = "0";
}
</script>
<input type="button" value="Add to Hunger" onclick="handleClick()" /><br />
<span id="output">0</span>
where hunger is defined as a global variable (integer) in another frame.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.