1. Home
  2. Computing & Technology
  3. JavaScript

Counting With Buttons

1. Input Field

clr gif
Join the Discussion

Questions? Comments?

More of this Feature

Plain Text

Here is a rather interesting form field that we can construct using Javascript. This input field is not intended to be entered directly, instead the value in the field is updated by selecting the buttons on either side of the field as many times as is required to update the field to the required value. Here is an example:

This effect is fairly easily achieved. All that you need to do is to copy the following simple Javascript code into the head section of your page and then access the functions from within the form.

var cnt = 0;
function add() {cnt++;set();}
function sub() {cnt--;set();}
function set() {myform.count.value = cnt;}

You can of course modify the code within the add() and sub() functions if you require that the field value be kept between specific boundary values.

The actual coding of the form to achieve this effect is as follows. Note that the onblur processing sets the value of the field back to whatever value was in the field before so as to effectively prevent the field from being updated directly.

<form name="myform">
<input type="button" value="-"
onclick="sub()" /><input type="input"
value="0" size="3" name="count"
onblur="set();" /><input type="button"
value=" + " onclick="add()" />
</form>

With a little more work we can do away with the input field and directly update the plain text between the buttons.

Input Field | Plain Text
Explore JavaScript
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.