473,566 Members | 2,772 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Suddenly, a NaN error in Netscape

Hi!

I've modified a javascript order form calculation script that tallies
up the subtotal, shipping/handling, and total automatically.

I did some modifications and it still worked fine, even in Netscape,
but at some point the Shipping/Handling field has ceased to display
correctly in that browser, showing a Not A Number error. (In Safari it
looks fine, and it calculates correctly in all browsers I've tested it
with.)

http://wiseowlmultimedia.com/learnin...s_orderUS.html

I'm no java genius, just a copy-paste-and-tinker boy, so I've
basically got no clue what I messed up. My fine-tooth comb has turned
up no reason I can see why it broke. Can anyone help?

Thanks!
Adam

PS - It does act a bit peculiar in IE - I found I needed to click on
all the subtotal fields to make them show anything - but I suppose
that's just a java quirk of Explorer...
Jul 23 '05 #1
17 1771
On 10 Aug 2004 14:17:33 -0700, Adam <ad********@sha w.ca> wrote:

[snip]
I did some modifications and it still worked fine, even in Netscape,
but at some point the Shipping/Handling field has ceased to display
correctly in that browser, showing a Not A Number error. (In Safari it
looks fine, and it calculates correctly in all browsers I've tested it
with.)

http://wiseowlmultimedia.com/learnin...s_orderUS.html

I'm no java genius, just a copy-paste-and-tinker boy, so I've
basically got no clue what I messed up. My fine-tooth comb has turned
up no reason I can see why it broke. Can anyone help?


[snip]

There are numerous possible causes in your code. Because of this, I
thought it easier to rewrite the script. That way, I also demonstrate some
more robust ways of accomplishing the things you were doing.

function totalItem(i, e) {
/* Get references to the form controls. */
var oP = e['Item' + i + 'Price'],
oQ = e['Item' + i + 'Quantity'],
oT = e['Item' + i + 'Total'];
/* Get the values and convert them to numbers. */
var p = +oP.value, q = +oQ.value, t;

/* Check that price and quantity are positive,
* finite numbers. If not, quit now. */
if(isNaN(p) || isNaN(q) || p < 0 ||
q < 0 || !isFinite(p) || !isFinite(p)) {return;}

/* A quantity shouldn't have a fractional
* part, so let's remove it. */
oQ.value = String(q = Math.floor(q));

/* Calculate total and round. */
t = Math.round((p * 100) * q) / 100;

/* Convert the total to a formatted
* string and update the form. */
oT.value = toCurrency(t, '$', ',');
return t;
}

function totalOrder() {
var e = document.forms['orderform'].elements,
n = 40,
t = 0,
s;

/* Loop through items 1..n, computing the item
* total and adding it to the order total. */
for(var i = 1; i <= n; ++i) {
var x = totalItem(i, e);

/* Check for an error. */
if('undefined' == typeof x) {
alert('Item ' + i + ' contains an invalid value.\n' +
'Please correct it and try again.');
e['Item' + i + 'Quantity'].focus();
return;
}
t += x;
}
/* Less than $100, add 15%; $100 or more, add 10% */
s = Math.round(t * ((t < 100) ? 0.15 : 0.1) * 100) / 100;
/* Update the final totals. */
e['OrderTotal'].value = toCurrency(t, '$', ',');
e['SH'].value = toCurrency(s, '$', ',');
e['GrandTotal'].value = toCurrency(t + s, '$', ',');
}

/* n - Number to format.
* c - Currency symbol to use.
* g - Grouping symbol.
*
* Outputs a number of the form cngnnngnnn.nn
*
* For example, toCurrency(1426 .356, '£', ',') produces
* £1,426.36
*/
function toCurrency(n, c, g) {
var s = (0 > n) ? '-' : ''; n = Math.abs(n);
var m = String(Math.rou nd(n * 100));
var j, i = '', f;

while(m.length < 3) {m = '0' + m;}
f = m.substring((j = m.length - 2));
while(j > 3) {
i = g + m.substring(j - 3, j) + i;
j -= 3;
}
i = m.substring(0, j) + i;
return s + c + i + '.' + f;
}

I've tested this briefly and everything seemed fine, but I don't
anticipate any problems.

A quick note:

<script language="JavaS cript">
<!--

The SCRIPT element requires the type attribute. This attribute makes the
language attribute redundant. Furthermore, the practice of script hiding
is obsolete. Even if a particular browser doesn't execute scripts, all
browsers now in use at least understand what a SCRIPT element is. Change
these lines to:

<script type="text/javascript">

In addition, you should really update the page to use CSS properly, and
remove all presentational HTML. That stuff was declared deprecated long
ago. It would be beneficial to your visitors to specify a print stylesheet
so that they don't print extraneous information when they make an order.

Finally, I strongly suggest that you read the group FAQ
(<URL:http://jibbering.com/faq/>), particularly sections 4.12, 4.39 (and
its link) and 4.40.

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail
Jul 23 '05 #2
ad********@shaw .ca (Adam) wrote in message news:<84******* *************** ****@posting.go ogle.com>...
Hi!

I've modified a javascript order form calculation script that tallies
up the subtotal, shipping/handling, and total automatically.
http://wiseowlmultimedia.com/learnin...s_orderUS.html


When I typed in a q in the quantity field, I got Nan. Seems
semi-reasonable. An error message would have been better. When I put
in a number, I got back numbers.

A guantity of 1.5 gave the unrealistic price of 1.5 time the price for
one item.

The page worked with valid numbers.

You get what you pay for.

Robert
Jul 23 '05 #3

Well, "thanks" doesn't even begin to cover it! But... thanks, Michael!

I must reluctantly ask one more question: what do I do to the function
references in the Quantity fields to get it to work?

I thought that

onchange="Total ();"

would need to become

onchange="total Order();"

since that appears to be the new name of the function, but currently the
script doesn't work at all...

It's at the same link:

http://wiseowlmultimedia.com/learningaids/
learningaids_or derUS.html

Thanks for the one additional bit of help Michael!

Adam

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #4
JRS: In article <opscjkffb0x13k vk@atlantis>, dated Wed, 11 Aug 2004
00:16:52, seen in news:comp.lang. javascript, Michael Winter <M.Winter@bl
ueyonder.co.inv alid> posted :
On 10 Aug 2004 14:17:33 -0700, Adam <ad********@sha w.ca> wrote:
I'm no java genius, just a copy-paste-and-tinker boy, so I've
basically got no clue what I messed up.


You should not, therefore, be doing work with financial or possibly
legal consequences. It's cheaper to employ a competent programmer first
than a lawyer after - unless, of course, you work in a law firm.
[snip]

There are numerous possible causes in your code. Because of this, I
thought it easier to rewrite the script. That way, I also demonstrate some
more robust ways of accomplishing the things you were doing. /* A quantity shouldn't have a fractional
* part, so let's remove it. */
oQ.value = String(q = Math.floor(q));
No. If data is clearly wrong, the data-enterer should be made to
correct it; the programmer cannot reliably correct what was intended.

I'd also reject (in most circumstances) any price with a decimal point
and then not-two digits; and might require the decimal point.

IMHO, data strings should be tested FIRST by RegExps - for example, if a
user types 1e5 instead of 135, ISTM that your code cannot detect it.

<URL:http://www.merlyn.demo n.co.uk/js-valid.htm>
I've tested this briefly and everything seemed fine, but I don't
anticipate any problems.


Provided that the result does not exceed a little over (1e19 - 10000)
monetary units.
--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> JL / RC : FAQ for news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #5
On Wed, 11 Aug 2004 14:09:35 +0100, Dr John Stockton
<sp**@merlyn.de mon.co.uk> wrote:
JRS: In article <opscjkffb0x13k vk@atlantis>, dated Wed, 11 Aug2004
00:16:52, seen in news:comp.lang. javascript, Michael Winter
<M.******@bluey onder.co.invali d> posted :
/* A quantity shouldn't have a fractional
* part, so let's remove it. */
oQ.value = String(q = Math.floor(q));
No. If data is clearly wrong, the data-enterer should be made tocorrect
it; the programmer cannot reliably correct what wasintended.


Usually, I wouldn't hesitate to agree, but the correction in this case is
clear. However, it is probably better to just notify the user and let them
correct it. At least then they don't think, "Hey! What happened to that
number I entered there?".
I'd also reject (in most circumstances) any price with a decimalpoint
and then not-two digits; and might require the decimal point.
The prices are preset on the page. They shouldn't need to be checked, but
in case they are altered to something non-numeric, I thought I'd check
them to avoid errors. Really, it would be better to show the prices and
totals as simple text (not as form control values), but that would then
require recent DOM-conforming browsers and I don't think the minor
increase in security is worth alienating lots of older browsers.
IMHO, data strings should be tested FIRST by RegExps - for example,if a
user types 1e5 instead of 135, ISTM that your code cannotdetect it.
Yes, you're right there. Though the validity of the number is easy enough
to check simply by attempting to convert from string, illogical values
such as those given in scientific notation can't be checked other than
with the original string. Also numbers containing thousand separators
won't be converted.
<URL:http://www.merlyn.demo n.co.uk/js-valid.htm>


By the way, there's an error in one of the text examples - Numeric
Patterns, RegExp examples, Money (2 optional digits). The regular
expression you have at the moment is:

/^\d+(\.\d{2})$/

You missed the question mark. It should be:

/^\d+(\.\d{2})?$/
I've tested this briefly and everything seemed fine, but I don't
anticipate any problems.


Provided that the result does not exceed a little over (1e19 -10000)
monetary units.


Yes, there is that. But I think we're heading for extremes (too extreme),
there.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail
Jul 23 '05 #6
On 11 Aug 2004 05:24:19 GMT, Adam Abrams <ad********@sha w.ca> wrote:
Well, "thanks" doesn't even begin to cover it! But... thanks, Michael!
You're welcome. If you do know how to reproduce the errors with the old
script, I suggest you try the same things with the new script.
I must reluctantly ask one more question: what do I do to the function
references in the Quantity fields to get it to work?
Sorry, I should have mentioned that totalOrder() replaced Total().
I thought that

onchange="Total ();"

would need to become

onchange="total Order();"

since that appears to be the new name of the function, but currently the
script doesn't work at all...


Funny. It works on all of my browsers (Opera, IE and Mozilla), exactly as
the old script did. You're not overlooking the fact that focus must leave
the control in order for the change event to fire, are you? The name of
the function is the only change to the interface.

After reading Dr Stockton's message, I think some changes to totalItem()
are in order. The new function is:

function totalItem(i, e) {
/* Get references to the form controls. */
var oP = e['Item' + i + 'Price'],
oQ = e['Item' + i + 'Quantity'],
oT = e['Item' + i + 'Total'];
/* Get the values (convert them later). */
var p = oP.value, q = oQ.value, t;

/* Check that price is a well-formatted
* decimal. If not, quit. */
if(!/^(([1-9]\d*)|0)\.\d{2}$/.test(p)) {return;}
/* Convert price. */
p = +p;

/* Check that quantity is a positive
* integer. If not, quit. */
if(!/^([1-9]\d*)|0$/.test(q)) {return;}

/* Calculate total. */
t = p * q;

/* Convert the total to a formatted
* string and update the form. */
oT.value = toCurrency(t, '$', ',');
return t;
}

In addition to the modified checks, I removed the rounding when
calculating the total. As 'q' will always be an integer, the value will
never go beyond two decimal places, making the rounding redundant. The
same is true for the rounding when calculating 's' in totalOrder(). Whilst
the value will go beyond 2dp there, the only calculation involving that
value is an addition, so there's no noticable effect. If you want to
simplify it a bit, change:

s = Math.round(t * ((t < 100) ? 0.15 : 0.1) * 100) / 100;

to

s = t * ((t < 100) ? 0.15 : 0.1);

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail
Jul 23 '05 #7

Hi guys!

I appreciate the highly pertinent and relevant issues you're both
pointing
out. But as I did point out, I am having a bit of difficulty simply
getting
the form to work with the new script. I do still need a little help over
here... 8^)

I assume I've mis-named the reference to the function which tallies
everything up, but, Michael, I would very much appreciate if you took a
quick peek and let me know if that's the case.

http://tinyurl.com/6w4n7

Please, guys, don't forget about me in this whole data-validation
debate!
8^)

Once again, many thanks!

Adam

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #8

Hi Michael,

Guess our last messages crossed each other - thanks for the extra info.
I
suspected the funtion name had changed, and I have corrected that, and
I did indeed realize to "tab out" of the field to activate the
function... but
the script still doesn't currently work for me - in IE, Netscape 4.77,
or
Safari. The old script (previous to yours) worked in all of them, at
least
originally before I tinkered with it (and still "sort of" worked
afterward).
But now - nothing.

Hope you can help!
Adam

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #9
On 11 Aug 2004 23:04:15 GMT, Adam Abrams <ad********@sha w.ca> wrote:

[snip]
I suspected the funtion name had changed, and I have correctedthat, and
I did indeed realize to "tab out" of the field toactivate the function...
I assumed you did, but as I said then, and I maintain now, there is
nothing wrong with the script, apart from what Dr Stockton pointed out
with regard to validation.
but the script still doesn't currently work for me - in IE,Netscape
4.77, or Safari. The old script (previous to yours) workedin all of
them, at least originally before I tinkered with it (andstill "sort of"
worked afterward).
But now - nothing.


After downloading NN 4.77, I found that it was complaining about invalid
characters. I downloaded the file, made a copy, and reformatted the
script. It worked fine.

It seems that Netscape is correct; there are invalid characters in the
file. When I examined it with a binary editor, the indentation is made
with character code 160 (0xA0). I don't know why, but either you
inadvertantly inserted them, your editor did, or your news reader did when
you copied my post. Check the file format your editor uses. Make sure it
uses plain or ANSI text.

In case you can't find out the cause, I've hosted the script as a .js file
on my web server:

<URL:http://www.mlwinter.pw p.blueyonder.co .uk/clj/abrams/validation.js>

It includes all the changes I've mentioned since the original post.

Copy that to your server and replace the SCRIPT block with

<script type="text/javascript" src="validation .js"></script>

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
4825
by: Mr. x | last post by:
Hello, I wrote a javascript, and when I open the html by the browser, I get the message : Error in page. It is about tousand lines, and I cannot figure out in a simple way, where is the line, that cause the error ? I see on other computers, a message like " ... do you wish to debug".
5
6371
by: Dan Tartakovsky | last post by:
Hi, folks. Does this error below look familiar to you? I'm trying to access function in one frame from the other frame. Error is received while working with Opera or Netscape (different errors). No problems are encountered with Microsoft IE - everything works fine. Any ideas about direction? // Opera error
2
2090
by: Simon | last post by:
I have recently set up a server certificate on a web site. Under certain conditions I need to change the color of a html span element. I do this using the following javascript function called from the onreset attribute of the form element. function removeWarningMsg() { if (isIE) { document.all.Warning.style.color =...
1
1661
by: questionr | last post by:
There is a spell checker function which is written in VB Script. The function works well when tested seperately. But when the function is called from Java Script, the function shows an Error saying " A run time error has occured. Do you wish to debug? Line :0 , Object Expected". I just know that it is a Java Script error. Any suggestions on...
6
6775
by: David Cook | last post by:
The html file below gets intermittent errors 'error on page' ('number expected') when clicking on column-headings to sort. Yet, this same file works flawlessly in other browsers (i.e. Opera, Mozilla, Netscape, etc.). Can anyone suggest a fix/workaround? Cheers...
8
3095
by: Dean Speir | last post by:
Hi... I've been referred to this Newsgroup by the W3C Markup Validator FAQ. I've been happily using this Validator <http://validator.w3.org> for the past 18 months with great success, but suddenly I cannot get it to "read" my HTML documents by the "Validate by File Upload" method. It keeps giving me the following message: Sorry, I am...
12
1723
by: melanieab | last post by:
Hi, I have a button that, when clicked, saves all the info entered. It worked fine until suddenly it didn't, and I have no idea why. I get the error An unhandled exception of type 'System.Xml.XmlException' occurred in system.xml.dll Additional information: System error. I found that this sometimes happens when there's some unrecognized...
3
1393
by: Jack Fox | last post by:
I just upgraded my XP development machine to SP2, upgraded dotnet framework 1.1 to sp1, and applied every other outstanding security patch, and suddenly Server.Transfer in my asp.net website no longer works. I get: Invalid path for child request 'Browse.aspx?&p=4&q=14569:10.1.0.4;14581:3:6.0:7.3'. A virtual path is expected. What does it...
1
1502
by: teddysnips | last post by:
I recently had to rebuild an instance of SQL Server. When it was restarted, one of the client apps (ASP.NET) could not connect - the user could see the login screen, but it kept throwing exceptions. Turns out that the database had been restored with a different name, so the connection string (stored in web.config) was amended. At that...
0
7584
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7888
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7644
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7951
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6260
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3643
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2083
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1201
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.