When creating forms, you might have encountered the following issue: You want a field with a number, that has to be within a certain range and have no fractions or decimals. One way of doing that is to provide a dropdown with all the possible numbers as options. This solution has some drawbacks, mainly the complexity of the dropdown (when thinking of keyboard users and users with visual impairments) and the restriction to a small range of numbers.
Another option is a free text entry field that will be validated on the backend.
To make it easier for the user we can also use Javascript to validate the field when the user leaves it and provide links that increase or decrease its value. These should only appear when Javascript is enabled.
To achieve the above functionality, all you need to do is to embed the file createcounter.js in your HTML document:
<script type="text/javascript" src="createcounter.js"></script>
Furthermore, you need to add a special class to each text field that should become a counter:
<input type="text" size="3" name="passenger" class="counter_1_12" value="1" />
The syntax of the class is the following:
counter_(minimum value needed)_(maximum value needed)
counter_0_10
counter_-10_10
counter_1_999
The links that get generated get the class counterlink
applied to them,
and you can use CSS to style them any way you want. This class name, and the
texts that get displayed in the links can be customised in the variable part
of the script:
var linkclass='counterlink'; var addtext='+'; var subtext='-';
Furthermore, you can define if the subtracting link should appear before
or after the input by setting the variable addbefore
to true
or
false
.