View Full Version : counting with buttons

08-09-2005, 02:23 PM
Please keep in mind that I know very little of javascript.

I found this code:

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;

<form name="myform">
<input type="button" value="-" onclick="sub()" />
<span id="mycnt">0</span>
<input type="button" value=" + " onclick="add()" />


It is exactly what I am needing to do, but I need multiple of them all the same page. Whenever I add another form with the buttons, of course, it breaks since the script only will call the "myform" form.

Since I am going to be needing about 50 of these on the same page, I dont want the javascript to be huge.

How can I do this? Please please help. It is very much appreciated!


Johnny Lang
08-09-2005, 02:48 PM
<Script Language=JavaScript>

function update(isField,toSum){

currCount = parseInt(isField.value);
newCount = currCount+toSum;
isField.value = newCount;

<Form name='counters'>
Counter 1:
<input type=button value="+" onclick="update(this.form.counter1,1)">
<input type=button value="-" onclick="update(this.form.counter1,-1)">
<input type=text size=10 name='counter1' value=0 readonly>
Counter 2:
<input type=button value="+" onclick="update(this.form.counter2,1)">
<input type=button value="-" onclick="update(this.form.counter2,-1)">
<input type=text size=10 name='counter2' value=0 readonly>
Counter 3:
<input type=button value="+" onclick="update(this.form.counter3,1)">
<input type=button value="-" onclick="update(this.form.counter3,-1)">
<input type=text size=10 name='counter3' value=0 readonly>

08-09-2005, 03:04 PM

Thank you SOOOOO much!

Johnny Lang
08-09-2005, 03:07 PM
I'm nothing of the sort, but you are welcome.