1. Home
  2. Computing & Technology
  3. JavaScript

Counting With Buttons

2. Plain Text

clr gif
Join the Discussion

Questions? Comments?

More of this Feature

Input Field

By the addition of a whole lot more code we can get rid of the need to have the count enclosed in an input field. This version should work in all current browsers but may not function in some earlier ones. Here is an example:

0

Here's the Javascript code (with the additions and changes shown in bold):

var aDOM = 0, ieDOM = 0, nsDOM = 0
var stdDOM = document.getElementById;
if (stdDOM) aDOM = 1; else {
ieDOM = document.all;
if (ieDOM) aDOM = 1; else {
var nsDOM = (
(navigator.appName.indexOf('Netscape') != -1)
&& (parseInt(navigator.appVersion) ==4));
if (nsDOM) aDOM = 1;
}
}

function xDOM(objectId) {
if (stdDOM)
return (document.getElementById(objectId));
if (ieDOM) return (document.all[objectId]);
if (nsDOM) return (document.layers[objectId]);
}


var cnt = 0;
function add() {cnt++;set();}
function sub() {cnt--;set();}
function set() {
var obj = xDOM('mycnt');
obj.innerHTML = cnt;

}

And here is the amended HTML (again with the changes shown in bold):

<form name="myform">
<input type="button" value="-"
onclick="sub()" />
<span id="mycnt">0</span>
<input type="button"
value=" + " onclick="add()" />
</form>
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.