Can I create a javascript variable and increment that variable when I press a button (not submit the form). Thanks!
-
5This question should have a title like "how to increment a JavaScript variable based on a web page button press event".Parappa– Parappa2009-05-08 00:35:49 +00:00Commented May 8, 2009 at 0:35
-
4@Parappa you should have edited it thenShadowpat– Shadowpat2013-05-03 00:23:05 +00:00Commented May 3, 2013 at 0:23
9 Answers
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>
1 Comment
<script type="text/javascript">
var i=0;
function increase()
{
i++;
return false;
}</script><input type="button" onclick="increase();">
5 Comments
button does not submit a form. A submit does.return false in the function to have any effect, you need to do onclick="return increase();".I needed to see the results of this script and was able to do so by incorporating the below:
var i=0;
function increase()
{
i++;
document.getElementById('boldstuff').innerHTML= +i;
}
<p>var = <b id="boldstuff">0</b></p>
<input type="button" onclick="increase();">
add the "script" tag above all and a closing script tag below the function end curly brace. Returning false caused firefox to hang when I tried it. All other solutions didn't show the result of the increment, in my experience.
Comments
Use type = "button" instead of "submit", then add an onClick handler for it.
For example:
<input type="button" value="Increment" onClick="myVar++;" />
1 Comment
Had a similar problem. Needed to append as many text inputs as the user wanted, to a form. The functionality of it using jQuery was the answer to the question:
<div id='inputdiv'>
<button id='mybutton'>add an input</button>
</div>
<script>
var thecounter=0; //declare and initialize the counter outside of the function
$('#mybutton').on('click', function(){
thecounter++;
$('#inputdiv').append('<input id="input'+thecounter+'" type="text/>);
});
</script>
Adding the count to each new input id resulted in unique ids which lets you get all the values using the jQuery serialize() function.