Can I create a javascript variable and increment that variable when I press a button (not submit the form). Thanks!
+9
A:
Yes:
<script type="text/javascript">
var counter = 0;
</script>
and
<button onclick="counter++">Increment</button>
Tomh
2009-05-08 00:10:56
I was typing it, when you posted it.
Unkwntech
2009-05-08 00:12:05
I fixed your button html.
Unkwntech
2009-05-08 00:13:23
My button html is fine..
Tomh
2009-05-08 00:15:06
You had an open input tag and a close button tag.
lc
2009-05-08 00:16:57
+2
A:
<script type="text/javascript">
var i=0;
function increase()
{
i++;
return false;
}</script><input type="button" onclick="increase();">
balint
2009-05-08 00:11:25
with "return false" stated in the function or in the onclick event, it will not post the form.
balint
2009-05-08 00:16:27
A:
Yes.
<head>
<script type='javascript'>
var x = 0;
</script>
</head>
<body>
<input type='button' onclick='x++;'/>
</body>
[Psuedo code, god I hope this is right.]
Joshua Belden
2009-05-08 00:11:36
A:
yes, supposing your variable is in the global namespace:
<button onclick="myVar += 1;alert('myVar now equals ' + myVar)">Increment!!</button>
rgz
2009-05-08 00:12:03
A:
Use type = "button"
instead of "submit"
, then add an onClick
handler for it.
For example:
<input type="button" value="Increment" onClick="myVar++;" />
lc
2009-05-08 00:12:59
A:
I believe you need something similar to the following:
<script type="text/javascript">
var count++
function increment(){
count++;
return false;
}
</script>
...
and
<input type="button" onClick="increment()" value="Increment"/>
or
<input type="button" onClick="count++" value="Increment"/>
xgMz
2009-05-08 00:21:47
+2
A:
The purist way to do this would be to add event handlers to the button, instead of mixing behavior with the content (LSM, Layered Semantic Markup)
<input type="button" value="Increment" id="increment"/>
<script type="text/javascript">
var count = 0;
// JQuery way
$('#increment').click(function (e) {
e.preventDefault();
count++;
});
// YUI way
YAHOO.util.Event.on('increment', 'click', function (e) {
YAHOO.util.Event.preventDefault(e);
count++;
});
// Simple way
document.getElementById('increment').onclick = function (e) {
count++;
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
};
</script>
Sudhee
2009-05-08 05:04:39