Adding 1 to form field with button

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Coladude
    New Member
    • Mar 2008
    • 1

    Adding 1 to form field with button

    Hi,

    I´m building a form and decided to throw myself at some Javascript, even though im definetely no expert. Thats why i now need help :-/

    I´m building a fairly simple HTML form where the user types in data about himself.

    One of the form fields contain the number 0 which can then be changed by the user manually (which then results in some calculations etc...). However i would very much like to have a button that is able to add 1 to the form field when it is clicked - also it would be nice to have one that subtracts 1.

    I am guessing i need a piece of code that adds +1 (or subtracts) from the value of the form field? But how i would do that i have no idea. I hope someone here can help me out?

    Thx for the help and a great place to learn Javascript :-)
  • johnhjohn
    New Member
    • Dec 2006
    • 43

    #2
    Here is an example that will add or subtract one:

    Code:
    <html>
    <head>
    
    <script language="javascript" type="text/javascript">
     var current;
     function add_subtract(numb)
     {
       current = parseInt(document.getElementById("number").value);	// gets value from text  (parseInt gets first occurrence of a number from text)
       current+=numb;	// adds variable numb to current
       document.getElementById("number").value = current;	// puts new value into text
     }
    </script>
    
    </head>
    <body>
    <input type="text" id="number" value="0">
    <input type="button" value="Add One" onclick="add_subtract(1)">
    <input type="button" value="Subtract One" onclick="add_subtract(-1)">
    
    </body>
    </html>
    I hope I helped.

    Comment

    Working...