By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,853 Members | 2,144 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,853 IT Pros & Developers. It's quick & easy.

Text Boxes addition

P: n/a
I post the same question few days ago but there was a confusion in the
answers. Anywayz I am posting again. I have a form with 96 textboxes
(8 rows x 12 columns)
Now I want in the last row to have the total of each row. The form
initially is loaded with zeros so Total would be zero. If a user
modifies a value, I want it immediately added in the coressponding box
at the end of each column.
Second question.. I want to validate every input not to be char but
only numbers.

I appriciate any help.

Thanks a lot
Marios Koumides
Jul 23 '05 #1
Share this Question
Share on Google+
7 Replies


P: n/a
Marios Koumides wrote:
I post the same question few days ago but there was a confusion in the
answers. Anywayz I am posting again. I have a form with 96 textboxes
(8 rows x 12 columns)
Now I want in the last row to have the total of each row. The form
initially is loaded with zeros so Total would be zero. If a user
modifies a value, I want it immediately added in the coressponding box
at the end of each column.
Then write a function that is called onchange of any text input that
updates all the sum fields. See the FAQ on how to read, convert to
number, add and re-insert the totals.
Second question.. I want to validate every input not to be char but
only numbers.


See the group FAQ, and its links.
--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Answer:It destroys the order of the conversation
Question: Why?
Answer: Top-Posting.
Question: Whats the most annoying thing on Usenet?
Jul 23 '05 #2

P: n/a
Marios Koumides wrote:
I post the same question few days ago but there was a confusion in the
answers. Anywayz I am posting again. I have a form with 96 textboxes
(8 rows x 12 columns)
Now I want in the last row to have the total of each row. The form
initially is loaded with zeros so Total would be zero. If a user
modifies a value, I want it immediately added in the coressponding box
at the end of each column.
Second question.. I want to validate every input not to be char but
only numbers.

I appriciate any help.


Here is an example of what you are trying to do. It attaches
events to the cells when you click the "attach events" button,
you should do it automatically when the page loads.

Note that the processing is dependent on the names of the cells
in the form.

Input is tested and must meet the test:

/^(\+|-)?\d+(\.)?(\d+)?$/

Which is a number with optional sign (+/-) and optional decimal
point and optional digits after the decimal.

If the cell value does not pass the test, the user is asked for a
valid input until they get it right - this is a bit nasty, you
may want to treat errors differently.

<form action="" name="ArrayOfInputs">
<table>
<tr>
<td><input type="text" name="c-0-0" value="0"></td>
<td><input type="text" name="c-1-0" value="0"></td>
<td><input type="text" name="c-2-0" value="0"></td>
</tr>
<tr>
<td><input type="text" name="c-0-1" value="0"></td>
<td><input type="text" name="c-1-1" value="0"></td>
<td><input type="text" name="c-2-1" value="0"></td>
</tr>
<tr>
<td><input type="text" name="c-0-2" value="0"></td>
<td><input type="text" name="c-1-2" value="0"></td>
<td><input type="text" name="c-2-2" value="0"></td>
</tr>
<tr>
<td><input type="text" name="c-0-t" value="0" readonly></td>
<td><input type="text" name="c-1-t" value="0" readonly></td>
<td><input type="text" name="c-2-t" value="0" readonly></td>
</tr>
<tr>
<td><input type="button" value="attach events" onclick="
initTable();
">&nbsp;</td>
<td><input type="reset"></td>
<td><input type="submit"></td>
</tr>
</table>
</form>
<script type="text/javascript">
function initTable(){
// Attach the event to all cells in the table
// except the ones with 't' in their name
var f = document.forms['ArrayOfInputs'];
var el = f.elements;
for (var i=0, eLen=el.length; i<eLen; i++){
if (el[i].type.toLowerCase() == 'text'
&& !el[i].name.match('t')) { // don't attach to totals
el[i].onchange = updateColumn;
}
}
}

function updateColumn(e){
// Get the cell that fired the event
var e = e || window.event;
var cell = e.target || e.srcElement;
var f = cell.form;
var n = cell.name.split('-');
var j = 0;
var t;
var sum = 0;
while ( (t = f.elements[n[0]+'-'+n[1]+'-'+j]) ){

// Check content, if OK add, else prompt
if ( testNum(t.value )) {
sum -= -t.value; // Using '-' forces t to be a number
} else {
while (!testNum(t.value)) {
t.value = prompt('Entries must be a number.'
+ '\nPlease enter a new value: ');
}
}
j++;
}
f.elements[n[0]+'-'+n[1]+'-'+'t'].value = sum;
}

function testNum(x) {
return /^(\+|-)?\d+(\.)?(\d+)?$/.test(x);
}
</script>




--
Rob
Jul 23 '05 #3

P: n/a
Marios Koumides wrote:
I post the same question few days ago but there was a confusion in the answers. Anywayz I am posting again. I have a form with 96 textboxes
(8 rows x 12 columns)
Now I want in the last row to have the total of each row. The form
initially is loaded with zeros so Total would be zero. If a user
modifies a value, I want it immediately added in the coressponding box at the end of each column.
Second question.. I want to validate every input not to be char but
only numbers.

I appriciate any help.

Thanks a lot
Marios Koumides


This needs some refining, but it's in the neighborhood, so to speak.
Name your textboxes whatever you like, just observe the table structure
given (easily modified). Table dynamically written for compactness.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>some phlegm</title>
<style type="text/css">

body {
background: #dca;
}
#phlegm {
margin: 50px auto;
}
#phlegm td.n {
font: bold 11px tahoma;
text-align: right;
}
#phlegm tr.tot input {
border: 1px #000 solid;
background: #edb;
}
#phlegm td input {
font: normal 11px tahoma;
text-align: center;
margin: 2px;
border-left: 1px #000 solid;
border-right: 1px #000 solid;
border-top: 1px #dca solid;
border-bottom: 1px #dca solid;
}

</style>
<script type="text/javascript">

var table_id = 'phlegm';
var inclass = 'data';
var totclass = 'colsum';
var ncols = 12;
var errmsg = 'Invalid input.';

function setTheTable()
{
if (!document.getElementsByTagName)
return;

function sumcol(e)
{
e = e || window.event || {};
var tgt = e.srcElement || e.target;
if (tgt && tgt.className == inclass)
{
var i = tgt.idx % ncols,
offset = ncols,
ipt,
v,
total = 0;
for (; i < grid.length; i += offset)
{
ipt = grid[i];
if (ipt.className == inclass)
{
v = ipt.value;
if (/^\s*$/.test(v))
ipt.value = '0';
else if (!/^[0-9]*$/.test(v)
&& e.type
&& /keyup/i.test(e.type))
{
alert(errmsg);
ipt.value = '0';
if (ipt.focus)
ipt.focus();
if (ipt.select)
ipt.select();
return;
}
else total += +v || 0;
}
else if (ipt.className == totclass)
ipt.value = total;
}
}
}

var el,
grid = [],
ipt,
i = -1;
if (el = document.getElementById(table_id))
{
var ipts = el.getElementsByTagName('input'),
re = new RegExp('((' + inclass + ')|(' + totclass + '))');
while (ipt = ipts.item(++i))
if (re.test(ipt.className))
{
ipt.idx = i;
grid[i] = ipt;
if (ipt.className == inclass)
{
ipt.onkeyup = sumcol;
ipt.onblur = sumcol;
}
}
}
}

window.onload = setTheTable;

</script>
</head>
<body>
<form>
<table id="phlegm">
<thead>
<tr>
<th></th>
<th>1</th><th>2</th><th>3</th><th>4</th>
<th>5</th><th>6</th><th>7</th><th>8</th>
<th>9</th><th>10</th><th>11</th><th>12</th>
</tr>
</thead>
<tbody>
<script type="text/javascript">
var r = 8, c;
while (r--)
{
document.write('<td class="n">',8-r,'</td>');
c = 12;
while (c--)
document.write(
'<td>' ,
'<input type="text" ' ,
'class="data" ' ,
'size="4" ' ,
'name="" ' ,
'value="0" />' ,
'</td>'
);
document.write('</tr>');
}
</script>
</tbody>
<tbody>
<tr class="tot">
<td class="n">totals:</td>
<script type="text/javascript">
c = 12;
while (c--)
document.write(
'<td>' ,
'<input type="text" ' ,
'class="colsum" ' ,
'size="4" ' ,
'name="" ' ,
'value="0" ' ,
'readonly="readonly"' ,
'/></td>'
);
</script>
</tr>
</tbody>
</table>
</form>
</body>
</html>

Jul 23 '05 #4

P: n/a
RobB wrote:
Marios Koumides wrote: [...]
answers. Anywayz I am posting again. I have a form with 96 textboxes
(8 rows x 12 columns)
Now I want in the last row to have the total of each row. The form
initially is loaded with zeros so Total would be zero. If a user
modifies a value, I want it immediately added in the coressponding


box
at the end of each column.
Second question.. I want to validate every input not to be char but
only numbers.

[...]

Rob, I like some of the concepts you have used. For the sake of
discussion, can I pose a few questions? I realise you haven't
taken this to the fullest for obvious reasons, but hopefully the
OP will get some further benefit.

This needs some refining, but it's in the neighborhood, so to speak.
Name your textboxes whatever you like, just observe the table structure
given (easily modified). Table dynamically written for compactness.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head> [...] <script type="text/javascript">

var table_id = 'phlegm';
var inclass = 'data';
var totclass = 'colsum';
var ncols = 12;
var errmsg = 'Invalid input.';
Could some (all?) of these globals be avoided? There seems to
be a dislike of globals, a discussion is here:
<URL:http://cleancode.sourceforge.net/wwwdoc/codingRules/vr1.html>

function setTheTable()
{
if (!document.getElementsByTagName)
return;
Is there *no* alternative? Or is the number of UA's that don't
support gEBTN small enough to be (reasonably) safely dismissed?

function sumcol(e)
{
e = e || window.event || {};
var tgt = e.srcElement || e.target;
if (tgt && tgt.className == inclass)
Since you seem to be going for more production-class code, it
seems reasonable to allow 'inclass' to match only whole words
and also to be detectable where multiple classes have been
specified:

...
var tgt = e.srcElement || e.target;
var cTest = new RegExp('\\b' + inclass + '\\b');
if ( tgt
&& tgt.className
&& cTest.test(inclass))
...

This would allow say every second or third row to be a different
colour by specifying a different (additional) class name to make
data entry easier. There may be a better way of matching whole
words, I created the above when I couldn't find a method - match
is too general here I think unless there are some qualifiers I
haven't discovered (more than likely...).
{
var i = tgt.idx % ncols,
offset = ncols,
ipt,
v,
total = 0;
for (; i < grid.length; i += offset)
{
ipt = grid[i];
if (ipt.className == inclass)
{
v = ipt.value;
if (/^\s*$/.test(v))
Forcing the contents to zero... that was asked for, but by
filling with zeros first, then only allowing digits for input,
it seems redundant.
ipt.value = '0';
else if (!/^[0-9]*$/.test(v)
The OP wanted 'only numbers' without specifying exactly what a
'number' is. If 'digit' was intended, then you've nailed it.
But perhaps a wider scope was intended? I dunno.
&& e.type
&& /keyup/i.test(e.type))
I don't like stuff happening on keyup (personal dislike),
probably because I'm a crap typist and make lots of mistakes so
when something is unforgiving of even a single key error, and
deletes my input so far so I have to start again, I get pissed
off. But that's personal preference.

This test also causes Firefox to dump a heap of
Exception/uncaught exception errors (which I think may be a bug
in Firefox rather than an error in your code).
{
alert(errmsg);
ipt.value = '0';
if (ipt.focus)
ipt.focus();
if (ipt.select)
ipt.select();
return;
}
else total += +v || 0;
}
else if (ipt.className == totclass)
ipt.value = total;
}
}
}

var el,
grid = [],
ipt,
i = -1;
if (el = document.getElementById(table_id))
{
var ipts = el.getElementsByTagName('input'),
re = new RegExp('((' + inclass + ')|(' + totclass + '))');
while (ipt = ipts.item(++i))
if (re.test(ipt.className))
{
ipt.idx = i;
grid[i] = ipt;
if (ipt.className == inclass)
{
ipt.onkeyup = sumcol;
Already mentioned keyup in regard to validating input, but it
also seems illogical to update the total before the user has
finished entering the entire number - again, just personal
preference. I also dislike things that change/move/update
whilst I'm typing - the less distraction, the better...

On the other hand, my use of onchange may not suit in all
situations either...
ipt.onblur = sumcol;

[...]

Generating the table dynamically is a good idea, saves on
download bandwidth, but it kinda stops the use of different
names on each input (unless an array of input field names is
also provided to add to the fields).

Generating the form may remove some of the flexibility provided
by using the properties of the grid to locate the elements to
update (does that make sense?).

Just thought a discussion of some of the features may help the
OP understand some pros/cons of whatever is ultimately
implemented.

--
Rob
Jul 23 '05 #5

P: n/a
RobG wrote:

(snip)
Rob, I like some of the concepts you have used. For the sake of
discussion, can I pose a few questions? I realise you haven't
taken this to the fullest for obvious reasons, but hopefully the
OP will get some further benefit.
Unless he's been kidnapped.

(snip)
Could some (all?) of these globals be avoided? There seems to
be a dislike of globals, a discussion is here:
<URL:http://cleancode.sourceforge.net/wwwdoc/codingRules/vr1.html>
Sheer laziness on my part.
function setTheTable()
{
if (!document.getElementsByTagName)
return;


Is there *no* alternative? Or is the number of UA's that don't
support gEBTN small enough to be (reasonably) safely dismissed?


Open to suggestion on that. And *please* don't say 'gEBTN' ('gEBI' is
affected enough).
function sumcol(e)
{
e = e || window.event || {};
var tgt = e.srcElement || e.target;
if (tgt && tgt.className == inclass)


Since you seem to be going for more production-class code...


(rotfl)
it seems reasonable to allow 'inclass' to match only whole words
and also to be detectable where multiple classes have been
specified:

...
var tgt = e.srcElement || e.target;
var cTest = new RegExp('\\b' + inclass + '\\b');
if ( tgt
&& tgt.className
&& cTest.test(inclass))
...

This would allow say every second or third row to be a different
colour by specifying a different (additional) class name to make
data entry easier.
Good call, generally do that.
{
var i = tgt.idx % ncols,
offset = ncols,
ipt,
v,
total = 0;
for (; i < grid.length; i += offset)
{
ipt = grid[i];
if (ipt.className == inclass)
{
v = ipt.value;
if (/^\s*$/.test(v))


Forcing the contents to zero... that was asked for, but by
filling with zeros first, then only allowing digits for input,
it seems redundant.


Somewhat hastily conceived, guilty.
The OP wanted 'only numbers' without specifying exactly what a
'number' is.
The OP specified 'every input not to be char but
only numbers', typically inconclusive. In these cases I generally avoid
complexity, until they get around to an actual description.
&& e.type
&& /keyup/i.test(e.type))


I don't like stuff happening on keyup (personal dislike),


This was to avoid a second alert() via the onblur handler, with the
usual cheery (endless) loop.
..probably because I'm a crap typist and make lots of mistakes so
when something is unforgiving of even a single key error, and
deletes my input so far so I have to start again, I get pissed
off. But that's personal preference.
'crap typist..' - is that a subspeciality of proctology? Good gig...

The alternative - onblur updating - is semantically bothersome to me,
as a blur (or change) signifies the user has already moved on and
focussed their attention elsewhere. More's the pity, there's no
'ongettingreadytomoveon' handler, so I prefer to update in real time as
data is entered. I think most folks can handle it (2005).
This test also causes Firefox to dump a heap of
Exception/uncaught exception errors (which I think may be a bug
in Firefox rather than an error in your code).
Don't see it, could be that old input focus bug...?
I also dislike things that change/move/update
whilst I'm typing - the less distraction, the better...
'whilst' is not a real word. All of you wholst insist upon saying it,
stop immediately. Why(lst) can't the English teach their children how
to speak?
Generating the table dynamically is a good idea...


Disagree on that #:-D only did it for the posting. Should have been
more explicit.

Hopefully we'll be hearing from the OPs kidnappers soon (whenst they
get to a phone, no doubt).

cheers, Rob

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/str*ict.dtd">
<html>
<head>
<title>dick nixon</title>
<style type="text/css">

body {
background: #383;
}
#nixon {
margin: 50px auto;
}
#nixon td.n {
font: bold 11px verdana, sans-serif;
text-align: right;
color: #fff;
border-width: 0;
}
#nixon tr.tot input {
height: 18px;
color: #fff;
padding-top: 5px;
border: 1px #fff solid;
background: #000;
}
#nixon th {
font: bold 11px verdana, sans-serif;
color: #fff;
}
#nixon td input {
font: normal 11px verdana, sans-serif;
text-align: center;
border: 1px #fff solid;
background: #eef;
}

</style>
<script type="text/javascript">

var config =
{
////////////////////////////
table_id: 'nixon' ,
inclass: 'data' ,
totclass: 'colsum' ,
ncols: 12 ,
errmsg: 'Invalid input.'
////////////////////////////
}

function setTheTable()
{
if (!document.getElementsByTagName
|| !document.getElementById)
return;

function sumcol(e)
{
e = e || window.event || {};
var tgt = e.srcElement || e.target;
if (tgt && ire.test(tgt.className))
{
var i = tgt.idx % config.ncols,
ipt, v, total = 0;
for (; i < grid.length; i += config.ncols)
{
ipt = grid[i];
if (ire.test(ipt.className))
{
v = ipt.value;
if (!/^[0-9]*$/.test(v)
&& e.type
&& /keyup/i.test(e.type))
{
alert(config.errmsg);
ipt.value = v.replace(/\D/g, '');
if (ipt.focus)
ipt.focus();
return;
}
else total += +v || 0;
}
else if (tre.test(ipt.className))
ipt.value = total;
}
}
}

var grid = [],
el, ipt, cls,
i = -1, idx = 0,
ire = new RegExp('\\b' + config.inclass + '\\b'),
tre = new RegExp('\\b' + config.totclass + '\\b');
if (el = document.getElementById(config.table_id))
{
var ipts = el.getElementsByTagName('input');
while (ipt = ipts.item(++i))
{
cls = ipt.className;
if (ire.test(cls) || tre.test(cls))
{
ipt.idx = idx++;
grid[i] = ipt;
if (ire.test(cls))
{
ipt.onkeyup = sumcol;
ipt.onblur = sumcol;
}
}
}
}
}

window.onload = setTheTable;

</script>
</head>
<body>
<form>
<table id="nixon">
<thead>
<tr>
<th></th>
<th>1</th><th>2</th><th>3</th>*<th>4</th>
<th>5</th><th>6</th><th>7</th>*<th>8</th>
<th>9</th><th>10</th><th>11</t*h><th>12</th>
</tr>
</thead>
<tbody>
<script type="text/javascript">
var r = 8, c;
while (r--)
{
document.write('<td class="n">',8-r,'</td>');
c = 12;
while (c--)
document.write(
'<td>' ,
'<input type="text" ' ,
'class="data" ' ,
'size="4" ' ,
'maxlength="4" ' ,
'name="" ' ,
'value="" />' ,
'</td>'
);
document.write('</tr>');
}
</script>
<tr class="tot">
<td class="n">column<br />totals</td>
<script type="text/javascript">
c = 12;
while (c--)
document.write(
'<td>' ,
'<input type="text" ' ,
'class="colsum" ' ,
'size="4" ' ,
'name="" ' ,
'value="0" ' ,
'readonly="readonly"' ,
'/></td>'
);
</script>
</tr>
</tbody>
</table>
</form>
</body>
</html>

Jul 23 '05 #6

P: n/a
RobB wrote:
[...]
..probably because I'm a crap typist and make lots of mistakes so
when something is unforgiving of even a single key error, and
deletes my input so far so I have to start again, I get pissed
off. But that's personal preference.

'crap typist..' - is that a subspeciality of proctology? Good gig...


I believe the usage of nouns as adjectives is suitable in
colloquial English - or is this news group to be restricted to
"the Queens English"? Gig(us) mirabilis?.

[...]
I also dislike things that change/move/update
whilst I'm typing - the less distraction, the better...

'whilst' is not a real word. All of you wholst insist upon saying it,
stop immediately. Why(lst) can't the English teach their children how
to speak?


"They should set a good example..."

Quoting the Lerner and Loewe musical version of that GBS classic
Pygmalion? Henry Higgins would like that... I believe the movie
version won 8 Oscars. Strangely, Lerner was an American and
Loewe an Austrian - no wonder it's such a great musical.

But you should have continued the quote:

"An Englishman's way of speaking absolutely classifies him
The moment he talks he makes some other Englishman despise him
One common language I'm afraid we'll never get

"Oh, why can't the English learn to

"Set a good example to people whose English
Is painful to your ears
The Scotch and the Irish leave you close to tears

"There even are places where English completely disappears
Well, in America, they haven't used it for years..."
--
Rob
Jul 23 '05 #7

P: n/a
RobG wrote:
RobB wrote:

[...]

'whilst' is not a real word. All of you wholst insist upon saying it,
stop immediately. Why(lst) can't the English teach their children how
to speak?

"They should set a good example..."

Quoting the Lerner and Loewe musical version of that GBS classic
Pygmalion? Henry Higgins would like that... I believe the movie
version won 8 Oscars. Strangely, Lerner was an American and
Loewe an Austrian - no wonder it's such a great musical.


I'm sure the satire of quoting a musical written by an American
and an Austrian based on an Irishman's play which itself is
based on a Ovid's telling of a Greek myth (circa 270 BC) about a
Cypriot king that satirises English pedantry with their language
is not lost on all.

"He's off his chump, he is."

No, not Monty Python, but Eliza Doolittle.
--
Zif
Jul 23 '05 #8

This discussion thread is closed

Replies have been disabled for this discussion.