tags:

views:

2132

answers:

8

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
I was typing it, when you posted it.
Unkwntech
I fixed your button html.
Unkwntech
My button html is fine..
Tomh
You had an open input tag and a close button tag.
lc
+2  A: 
<script type="text/javascript">
var i=0;

function increase()
{
 i++;
 return false;
}</script><input type="button" onclick="increase();">
balint
oh sure, go with the nice function call. :)
Joshua Belden
with "return false" stated in the function or in the onclick event, it will not post the form.
balint
Would it post the form being a button and not a submit?
Joshua Belden
if it's in a form, sure.
balint
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
yeah its fine...
Unkwntech
A: 

yes, supposing your variable is in the global namespace:

<button onclick="myVar += 1;alert('myVar now equals ' + myVar)">Increment!!</button>
rgz
A: 

Use type = "button" instead of "submit", then add an onClick handler for it.

For example:

<input type="button" value="Increment" onClick="myVar++;" />
lc
I prefer<button></button
rgz
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
+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
A: 

ella me taputan

seba