Counting With Buttons

HTML 5 proposes a new input field that is a spinning tool that allows a number to be selected based on specified minimum, maximum and step sizes. This new element sounds a lot like the one I created with JavaScript quite a few years ago which I called "counting with buttons".

Now the two variants of my original script were quite obtrusive and relied on JavaScript being enabled or they presented broken buttons to the user. In this new variant I am going to present those without JavaScript with a plain input field and replace it with an equivalent of the plain text version of my original script when JavaScript is enabled. The script even creates a hidden field with the same name as the id you pass to the script so the generated value can still be submitted with the form. The other thing I have implemented in this new almost unobtrusive version of the script is that you can now specify a minimum value, maximum value and step size just as you would for the proposed new HTML 5 element.

The only thing you will need to change to use this script are the four parameters being passed into the anonymous function at the end of the script. These are the id of the input field you are converting, the minimum value the field is allowed to have in it, the maximum value, and finally the step size to move the value by each time a button is clicked.

Here's an example that allows integers between zero and ten.

Counting With Buttons

To use this script simply attach the following JavaScript to the bottom of your web page and update the entries in the last line.


If you need multiple spinners in the same page then you may replace the anonymous self executing function wrapper with a function declaration so that you can call the function multiple times (once for each spinner). The modifications to do this are shown in bold below.

// Number Spinner
// copyright Stephen Chapman, 9th November 2012
// you may copy this script but please keep the copyright notice as well
var spinner = function(id,min,max,step) { "use strict";
var inp, hid, b1, b2, txt, frag, cnt, add, sub, set, createInput;
... all of this part of the script stays the same ...


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow