473,887 Members | 2,280 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to modify this script to allow negative numbers??

Hello Rob B posted this wonderful code in another thread,

http://groups.google.com/group/comp....ad9d5e61be85f0

I could not figure out how to reply to the thread per se using Google
Groups and so please forgive me for cutting and pasting (I emailed him
but he may not have time to check his email), and I am hoping someone
might be able to tell me how I can change this script to allow negative
numbers.

My question is:

How can I modify it to allow a minus sign to allow negative numbers??

I want to use it in a purchase requisition form where sometimes
negative numbers are necessary.

Ideally I want to allow a negative number typed in, then when it goes
to be printed I would want to reformat it (either with JS or CSS) so it
has ( ) to show it is
a negative/credit type of number for Accounts Payable to act
accordingly.

Thank you, Tom

The Chameleon Lives! :-)
Your welcome, Rogue.

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>untitled </title>
<script type="text/javascript">
//<![CDATA[

cF.RE1 = /^\d*\.?\d*$/;
cF.RE2 = /\.\d{3,}$/;
cF.RE3 = /\.(?=[^.]*\.)/g;
cF.RE4 = /[^\d.]/g;
cF.RE5 = /\.(?=[^.]*\.)/g;
cF.RE6 = /^(\d*\.\d{2}).+ $/;
cF.RE7 = /(\.\d{0,1})$/;
cF.RE8 = /^([^.]+)$/;

String.prototyp e.reverse = function()
{
return this.split(''). reverse().join( '');

}

function cF(fld, onblur)
{
var v = fld.value;
if (!cF.RE1.test(v ) || cF.RE2.test(v))
{
var ltdot = (fld.dotpos == v.indexOf('.') ?
v.lastIndexOf(' .') < fld.dotpos :
v.indexOf('.') < fld.dotpos);
if (ltdot)
v = v.reverse();
v = v.replace(cF.RE 3,'');
if (ltdot)
v = v.reverse();
v = v.replace(cF.RE 4,'').
replace(cF.RE5, '').
replace(cF.RE6, '$1');
fld.value = v;
}
fld.dotpos = v.indexOf('.');
if (onblur)
fld.value = v.replace(cF.RE 7, '$10').
replace(cF.RE7, '$10').
replace(cF.RE8, '$1.00');

}

//]]>
</script>
</head>
<body style="font:100 % arial;margin:30 0px;"
onload="f=docum ent.forms[0];f.reset();f.fo o.focus()">
<form onreset="foo.fo cus()">
$ <input type="text" name="foo" value="" size="10" maxlength="8"
style="font:75% arial;text-align:center;bo rder:1px black solid;"
onkeyup="return cF(this,false)"
onblur="return cF(this,true)" />
<input type="reset" value="clear" style="font:75% arial;border:1p x
black
solid;" />
</form>
</body>
</html>

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

Nov 27 '05 #1
11 11959
tlyczko wrote:
Hello Rob B posted this wonderful code in another thread,

http://groups.google.com/group/comp....ad9d5e61be85f0

I could not figure out how to reply to the thread per se using Google
Groups and so please forgive me for cutting and pasting (I emailed him
but he may not have time to check his email), and I am hoping someone
might be able to tell me how I can change this script to allow negative
numbers.
There's probably not much point in replying to a thread that is 12
months old.

My question is:

How can I modify it to allow a minus sign to allow negative numbers??

Very probably, but the script itself is very much more complex than need
be. What are you trying to do? If you want to restrict user input to 5
digits, one decimal point and two more digits, then use a regular
expression, there are many here that can be modified for your purpose:

<URL: http://www.merlyn.demon.co.uk/js-valid.htm#VNP >
The one you want is:

/^[-]?\d{0,5}(\.\d{0 ,2})?$/

I loath scripts that modify what I am typing as I type it. It is much
better to show a message adjacent to the input box to remind the user
that the format is not what you want and allow them to modify it. Many
users will simply type the extra digits anyway and likely not notice
that you've removed them. And if they have JavaScript disabled, your
script will not do anything.

Don't use an alert (especially as this seems to be for an intranet where
the users are likely experienced data input operators), that is even
worse. An example is below.
<script type="text/javascript">
//<![CDATA[

function testNum(num, erId){
var er = document.getEle mentById(erId);
var re = /^[-]?\d{0,5}(\.\d{0 ,2})?$/;
if (num && !re.test(num) ) {
er.innerHTML = 'Invalid number, required format is [-]nnnnn.nn';
} else {
er.innerHTML = '';
}
}

//]]>
</script>
</head><body>
<form action="">
$ <input type="text" name="foo" value="" size="10" maxlength="9"
onkeyup="testNu m(this.value, 'msg');" />
<input type="reset" value="clear" />
</form>
<div id="msg"></div>
</body>

I want to use it in a purchase requisition form where sometimes
negative numbers are necessary.
The above is not production ready, it just gives you a start and an
example of how to use a regular expression more efficiently.

Ideally I want to allow a negative number typed in, then when it goes
to be printed I would want to reformat it (either with JS or CSS) so it
has ( ) to show it is
a negative/credit type of number for Accounts Payable to act
accordingly.


Then use onblur to add the parenthesis. But you have limited the number
of characters in the input box, so how will you add the extra two
characters? If you modify the input's 'length' parameter, then the user
can go back, remove the brackets and add more numbers - so you have some
UI issues to deal with. Your original doesn't allow room for the minus
sign (unless you wanted 4 digits before the decimal).

Or do you write the value to somewhere else in the page?

[...]

--
Rob
Nov 28 '05 #2
Thank you for your help!!

I am RE-learning Javascript as I go. You were right, it was a
1-year-old thread, I gambled and hopefully we have something here
others can learn from.

Merlyn's Javascript pages are wonderful but I find them sometimes
rather abstract, because he uses a lot of includes to present things on
his site and sometimes the demos etc. require the include files, so it
can be a little difficult figuring out what to use.

Thank you for the specific link, though. I missed it completely when I
was reading his site before I found this script.

A few hours after posting, I also found a great website,
http://www.regexlib.com, which is a fantastic resource for regex
patterns.

I found one regex that although it is rather long, allows me to enter $
and enclosing parentheses (and even commas), which are necessary for
credits (to be subtracted) rather than debits (which will be added).
Purchase requisitions rarely have credits, usually everything is added
up.

The link for the regex is
http://www.regexlib.com/REDetails.aspx?regexp_id=625

You asked a couple of questions: 1. Yes, I do some calculations with
the numbers after they are entered; 2. Yes, I do need to modify the
regex to allow $ and ( ), I can figure this out, as well as how to do
the math for the totaling up, etc., I started this part already.

Just two questions:

1) Why did you use onkeyup?? I ask because I thought that one is
supposed to use onchange for testing values or doing something with
values, because I thought onkeyup catches every single keystroke, the
user would never finish typing the number.

2) What IS the best event for validating form field entries -- onblur,
onchange, onkeyup (I am posting this to the group too).

Thank you very much again.

:) tom

Nov 28 '05 #3
RobG wrote:
<script type="text/javascript">
//<![CDATA[
This is nonsense. Either you serve XHTML, then you should serve it as
application/xhtml+xml and need the declaration for easily legible inline
source code: user agents that support it, like Mozilla/5.0, will use their
faster XML parser that only accepts well-formed documents; user agents that
do not support it, like IE 6.x, will try to download it. Or you serve
HTML, then serve it as text/html where the tagsoup parser will be used and
CDATA declarations will have neither meaning nor will they be necessary
as the `script' element's content is PCDATA by default _only_ in XHTML.

The commented-out declaration was most certainly included in the attempt
to serve XHTML as text/html to achieve what XHTML 1.0, Appendix C, calls
"HTML compatibility". However, that section of the specification is
flawed; it is trying to achieve what cannot be achieved (since HTML and
XHTML are fundamentally different, especially in the meaning of the NET
delimiter), and it is potentially harmful since it relies solely on
afterwards non-specified error-correction by the user agent that, when
applied, _contradicted_ the HTML standard in this regard.

`<br />' in XHTML is `<br>&gt;' in HTML, _not_ `<br>', and CDATA content
will end at the first `</' not at `]]>'.
[...]
//]]>
</script>


<URL:http://hixie.ch/advocacy/xhtml>
PointedEars
Nov 28 '05 #4
tlyczko wrote:
Thank you for your help!!

I am RE-learning Javascript as I go. You were right, it was a
1-year-old thread, I gambled and hopefully we have something here
others can learn from.

Merlyn's Javascript pages are wonderful but I find them sometimes
rather abstract, because he uses a lot of includes to present things on
his site and sometimes the demos etc. require the include files, so it
can be a little difficult figuring out what to use.

Thank you for the specific link, though. I missed it completely when I
was reading his site before I found this script.

A few hours after posting, I also found a great website,
http://www.regexlib.com, which is a fantastic resource for regex
patterns.

I found one regex that although it is rather long, allows me to enter $
and enclosing parentheses (and even commas), which are necessary for
credits (to be subtracted) rather than debits (which will be added).
Purchase requisitions rarely have credits, usually everything is added
up.

The link for the regex is
http://www.regexlib.com/REDetails.aspx?regexp_id=625

You asked a couple of questions: 1. Yes, I do some calculations with
the numbers after they are entered; 2. Yes, I do need to modify the
regex to allow $ and ( ), I can figure this out, as well as how to do
the math for the totaling up, etc., I started this part already.

Just two questions:

1) Why did you use onkeyup?? I ask because I thought that one is
supposed to use onchange for testing values or doing something with
values, because I thought onkeyup catches every single keystroke, the
user would never finish typing the number.
I used keyup because that is what you posted code. As this seems like
an intranet application, you probably have users telling you what they
want. onblur will only fire when the focus moves on.

I just want you to be aware of the issues and can get your users to
pick what they want - implement it however you want. Often developers
force what they think should be done when the users have a much better
idea of the required functionality.


2) What IS the best event for validating form field entries -- onblur,
onchange, onkeyup (I am posting this to the group too).


Whatever your users like. If you use in-form error messages (like the
one I posted as an example but maybe you want to format it better)
then onkeyup is fine, just so long as the user's keystrokes aren't
affected. They see the message and can decide whether to ignore it or
not. Always keep the messages helpful and positive.

Check again on submit as they may have missed a message. :-)

--
Rob
Nov 28 '05 #5
Thomas 'PointedEars' Lahn wrote:
RobG wrote:

<script type="text/javascript">
//<![CDATA[

This is nonsense. Either you serve XHTML,


Talk to the OP Thomas.
[...]
--
Rob
Nov 28 '05 #6
Thank you, Thomas, for the comments about CDATA, though there was no
need to be so brusque.

RobG correctly observed this is an intranet app. However, it's on IE
6.x and someday later IE 7.x, so your "correct" way of serving the
document won't work for IE 6.x. It will become an included *.js file
anyway.

RobG, thank you again for your helpful answers...I will probably use
onchange as it is easier to understand initially, I have seen comments
about problems with onblur, and I don't yet understand the difference
between onchange and onblur, I need to read about this first.

I will try onkeyup too and see what happens, and I will use a simpler
regex / test mechanism than the code I posted at the beginning of this
thread.

Thank you again, everyone!!

:) tom

Nov 28 '05 #7
tlyczko wrote:
Thank you, Thomas, for the comments about CDATA,
though there was no need to be so brusque.


It was not the first time I explained it here.
PointedEars
Nov 28 '05 #8
Hi RobG (and anyone else who may know),

Thank you again for the sample code you provided above. For the most
part it does what I need it to do.

I tried out the sample code you gave me, it is very nice, onkeyup works
adequately, but how do I make the error message go away after they have
corrected the data input???

Should I add an onchange or onblur event with much the same code for
additional checking to see if the user has fixed the error???

I definitely should have the error message go away after they have
fixed it.

Thank you,
Tom

Nov 28 '05 #9
Note: I also found this website with these two links, which are going
to help me a lot.

http://www.rgagnon.com/jsdetails/js-0063.html

http://www.rgagnon.com/examples/jsregexp.html

Many useful regexp validations there, the only one missing is to allow
parentheses or negative numbers on currency values so they can be
"credits."

Thank you,
:) tom

Nov 28 '05 #10

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

Similar topics

2
3745
by: Mayank | last post by:
X-No-Archive: yes Hi, I have to replace all the negative numbers with 0 in a very large file. How can I do it in Perl/Awk. Negative numbers are of the format (-0.02:0.01:-1.00) ( 0.11:0.01:-0.01) I need to change them to
3
2624
by: eddie wang | last post by:
formatcurrency function puts ( ) for negative numbers(e.g. (111) ). How can I display the negative numbers with a minus sign infront like -111. Thanks. *** Sent via Developersdex http://www.developersdex.com *** Don't just participate in USENET...get rewarded for it!
7
8233
by: pj | last post by:
Why does M$ Query Analyzer display all numbers as positive, no matter whether they are truly positive or negative ? I am having to cast each column to varchar to find out if there are any negative numbers being hidden from me :( I tried checking Tools/Options/Connections/Use Regional Settings both on and off, stopping and restarting M$ Query Analyer in betwixt, but no improvement.
10
3022
by: KathyB | last post by:
Hi, I just can't get this quite right. I use the following function to validate a user entry. I need to allow negative numbers including those with decimals (e.g., -.5). The following allows the decimals but not the negative. Any help appreciated...as always. Thanks -- Kathy function ValidateSave(formRef,fieldName,min,max) { var formField = formRef.elements; if (!/^\d+(\.\d+)?$/.test(formField.value)) {
4
2150
by: Charles A. Lackman | last post by:
Hello, I have some textboxes that are doing addition: Dim AString As Double AString = Convert.ToDouble(TextBox1.Text) - Convert.To(DoubleTextBox2.Text) TextBox3.Text = AString.ToString("#,##0.00;(#,##0.00);0.00") When the result is negative it is displayed as "(46)" or whatever the value is.
39
4040
by: Frederick Gotham | last post by:
I have a general idea about how negative number systems work, but I'd appreciate some clarification if anyone would be willing to help me. Let's assume we're working with an 8-Bit signed integer, and that it contains no padding. Firstly, I realise that the MSB is known as the sign-bit, and that it indicates whether the number is positive or negative (irrespective of which negative number system is used).
20
5847
by: Casey | last post by:
Is there an easy way to use getopt and still allow negative numbers as args? I can easily write a workaround (pre-process the tail end of the arguments, stripping off any non-options including negative numbers into a separate sequence and ignore the (now empty) args list returned by getopt, but it would seem this is such a common requirement that there would be an option to treat a negative value as an argument. Note that this is only a...
2
13495
by: Jack Wales | last post by:
I need to set up a text box in Visual Basic which will only allow positive numbers and will produce an error message if 1 - A negative number is entered, 2 - something not numeric is entered and 3 - nothing is entered. Any help will be much appreciated. Thanks Jack
0
9957
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
11173
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10771
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10877
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
10434
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7143
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6011
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4633
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
2
4239
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.