...

View Full Version : Adding Comma to text field



mindlessLemming
06-30-2004, 02:40 PM
Hi guys :)
I've wandered into the JS forum because a recent client has asked for something that could only be done with js, if at all...

I would like to add a comma after every third number typed into an input field, while the number is being typed. The only catch is that the number (a dollar value) may also have decimal places, in which case the first comma wouldn't appear until 5 characters have been entered. Also, the comma would need to be stripped at time of submission.

The form in question is here (http://203.31.191.221/govtgrants.com/tools.php).
I've searched the forum and the web looking for a solution, but nothing does it as the user types... any suggestions will be warmly welcomed :D

sad69
06-30-2004, 06:57 PM
Well your page doesn't seem to be coming up, but I think you may be looking for a script like this:
http://lcognard.free.fr/javascri/patterns/formatage_financier.htm

Hope that helps,
Sadiq.

Willy Duitt
06-30-2004, 08:53 PM
It's not the most elegant script I've written
But it works onkeyup while the user is inputting....



<script type="text/javascript">
function format(input){
var num = input.value.replace(/\,/g,'');
if(!isNaN(num)){
if(num.indexOf('.') > -1){
num = num.split('.');
num[0] = num[0].toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'');
if(num[1].length > 2){
alert('You may only enter two decimals!');
num[1] = num[1].substring(0,num[1].length-1);
} input.value = num[0]+'.'+num[1];
} else{ input.value = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'') };
}
else{ alert('You may enter only numbers in this field!');
input.value = input.value.substring(0,input.value.length-1);
}
}
</script>
</head>

<body>
<form>
<input type="text" onkeyup="format(this)" onchange="format(this)"
onblur="if(this.value.indexOf('.')==-1)this.value=this.value+'.00'">
</form>


.....Willy

Edit: Fixed it so that only two decimals can be inputted.

sad69
06-30-2004, 09:17 PM
Hey cool, that works really well Willy!

Willy Duitt
06-30-2004, 09:54 PM
Thanks;

The toString().split().reverse().join() routine I picked up on this forum somewhere.
(sorry I forgot who posted it) All I did was put it together to work onkeyup.....

BTW: ML;

If you wish to strip the commas at submission you will need to add something like this to your form validation function:


document.forms[0]['MY_COMMA_INPUT'].value = document.forms[0]['MY_COMMA_INPUT'].replace(/\,/g,'');

mindlessLemming
07-01-2004, 02:23 AM
:thumbsup: Sweeeeet :thumbsup:
Thanks a lot guys, much appreciated!

Willy: do you want to PM me your real name so I can give you credit in the code? (I just like to do that, professional decency and all ;))

Thanks again :D

sad69
07-01-2004, 02:49 AM
What? That's not his real name? :eek:

;)
Sadiq.

Willy Duitt
07-01-2004, 03:28 AM
This is my name.
But don't worry about credits.
It only took a few minutes and quite frankly,
I merely mashed together things I learned here on the forum..... :)

.....Willy

stdesert
09-03-2004, 03:26 PM
I've been trying to use the function written by Willy to format numbers as they are being keyed in, but need to strip the commas at the time of submission.

I saw the post that says to add this to the form validation function:

document.forms[0]['MY_COMMA_INPUT'].value = document.forms[0]['MY_COMMA_INPUT'].replace(/\,/g,'');

My question is, what is my form validation function? (I know that sounds stupid, but I've never done any JS before the project I'm working on, and am learning bit by bit as I'm going.)

Currently, my form tag reads like this:
<form name="calculator" method="post" action="">

The only validation point I can think of is the Calculate button:
<input type=button value="Calculate." name="Calculate" onClick="calculate(this.form)">

But I can't see how the MY_COMMA_INPUT string fits into either one. Should I put it somewhere into the calculate(myform) function ? But where?

Someone suggested to me to put it at the beginning of the calculate function, but that it wouldn't work if the input is not the first element in the form. And, of course, the input is not the first element in the form...

Any suggestions?
This is a cool function, and I really would like to use it...

Thanks!

Willy Duitt
09-03-2004, 03:55 PM
You need to show us your form and calculate function...

The information you provided does not show your comma formatted input name nor how or what you are calculating... Normally, I would just advise to strip the commas out onsubmit but if you are performing any math calculations prior to submittal, the commas will need to be stripped in order for those values to be numbers and not strings...

BTW: I have changed the last else conditional to:



else{
var temp = input.value;
alert('You may enter only numbers in this field!');
input.value = temp.replace(/[^\$\d\.]*/g,'');
}


This fixes a problem of a user inputting an illegal character an the input losing focus to the alert and a decimal and trailing zeros corrupting the input onblur...

.....Willy

Willy Duitt
09-03-2004, 04:02 PM
Oh....

If you do not have a Calculate function... Try adding the replace onsubmit like so:



<script type="text/javascript">
function format(input){
var num = input.value.replace(/\,/g,'');
if(!isNaN(num)){
if(num.indexOf('.') > -1){
num = num.split('.');
num[0] = num[0].toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'');
if(num[1].length > 2){
alert('You may only enter two decimals!');
num[1] = num[1].substring(0,num[1].length-1);
} input.value = num[0]+'.'+num[1];
} else{ input.value = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'') };
}

else{
var temp = input.value;
alert('You may enter only numbers in this field!');
input.value = temp.replace(/[^\d\.]*/g,'');
}
}
</script>
</head>

<body>
<form name="calculator" method="post" action=""
onsubmit="this.input.value=this.input.value.replace(/\,/g,'')">
<input type="text" name="input" onkeyup="format(this)" onchange="format(this)"
onblur="if(this.value.indexOf('.')==-1)this.value=this.value+'.00'">
<input type="submit" value="Submit">
</form>


.....Willy

stdesert
09-06-2004, 04:46 PM
Willy,

Thanks for your help. :)
I made the change to the last else conditional statement, and was able to fix my problem by adding parseFloat and

.replace(/\,/g,'')
to the applicable variables as they are being declared at the beginning of the Calculate function, i.e.:


function calculate(myform) {
tier = (myform.tier.options[myform.tier.selectedIndex].value);
level = (myform.level.options[myform.level.selectedIndex].value);
product = (myform.product.options[myform.product.selectedIndex].value);
pricelevel = (myform.pricelevel.value);
pricelist = parseFloat(myform.pricelist.value.replace(/\,g,''));
materials = parseFloat(myform.materials.value.replace(/\,g,''));
mfg = parseFloat(myform.mfg.value.replace(/\,g,''));

with pricelist, materials, and mfg being the variables from which the commas need to be stripped before running the calculations. Worked like a charm.

I hope this makes sense. I sure appreciate your prompt response, and the tip for using this function without a Calculate function.

stdesert
09-21-2004, 02:07 PM
Hi,

I have one more question about the above function: how do you prevent it from inserting a comma after a minus sign when formatting a negative number inferior to 1,000?

In other words, how do you keep -167.00 from displaying as -,167.00?
Would you add parseFloat to this line?

} else{ input.value = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'') };
Unfortunately, I don't know enough JS to understand exactly how it works, and therefore wouldn't know how to modify it.

Thanks!

Willy Duitt
09-21-2004, 06:37 PM
Try this:



else{ input.value = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^(\-)?\,/,'$1') };

.....Willy

stdesert
09-27-2004, 05:35 PM
Thanks, Willy.

I tried the change you made in red, but I'm still getting a comma after the minus sign (i.e., -,254.00).

Is there anything else I could try?

Willy Duitt
09-27-2004, 06:01 PM
Don't know what to tell you...
It worked a week ago when I tested it...
Sorry but I don't have time to put it all together again...

.....Willy

stdesert
10-01-2004, 01:40 PM
Don't worry about it. I just discovered yesterday that there was something else interfering with it. Between your solution (adding '$1'), and fixing the other thing, I finally got it to work.

Thanks again for your help.

Willy Duitt
10-01-2004, 07:22 PM
I appreciate you returning and letting us know how you made out.... :cool:

I usually test any codes I post (unless otherwise noted) and I remember testing that expression but I also recall that I had to make changes to the function in order to even allow it to accept a negative number.... and I had already deleted those files so I was hoping you would return with an example of how you were using the script... But this is even better...

Congrats on getting it working yourself...
.....Willy

stdesert
05-10-2005, 11:54 PM
Hi Willy,

I need your help again with this function. (By the way, if you're not Willy, but have a solution, don't let that stop you :) )

In post #10 of this thread (dated 09-03-2004, 02:55 PM ), you said:



BTW: I have changed the last else conditional to:



else{
var temp = input.value;
alert('You may enter only numbers in this field!');
input.value = temp.replace(/[^\$\d\.]*/g,'');
}


This fixes a problem of a user inputting an illegal character an the input losing focus to the alert and a decimal and trailing zeros corrupting the input onblur...


Well, guess what: I have now been asked to allow some (but not all) of the input fields using that formatting function to accept negative numbers. I thought that removing parseFloat from these variables in the calculate function would do the trick, but it didn't (I still got a pop up message asking me to enter a numerical value in the field). I would be grateful for any suggestions.

Here is the entire formatting function as it stands, and the list of variables at the beginning of the calculate function representing the fields that need to be formatted upon input by the user. The fields that now need to accept negative numbers are: freightadj, premiums, and invadj.



function format(input){
var num = input.value.replace(/\,/g,'');
if(!isNaN(num)){
if(num.indexOf('.') > -1){
num = num.split('.');
num[0] = num[0].toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'');
if(num[1].length > 2){
alert('You may only enter two decimals!');
num[1] = num[1].substring(0,num[1].length-1);
} input.value = num[0]+'.'+num[1];
} else{ input.value = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'') };
}
else{
var temp = input.value;
alert('Please enter a numerical value in this field!');
input.value = temp.replace(/[^\$\d\.]*/g,'');
}
}
// End -->

function calculate(myform) {
level = myform.level.options[myform.level.selectedIndex].value;
tier = myform.tier.options[myform.tier.selectedIndex].value;
product = myform.product.options[myform.product.selectedIndex].value;
category = myform.category.value;
invoice = parseFloat(myform.invoice.value.replace(/\,/g,''));
materials = parseFloat(myform.materials.value.replace(/\,/g,''));
mfg = parseFloat(myform.mfg.value.replace(/\,/g,''));
ppvlist = parseFloat(myform.ppvlist.value.replace(/\,/g,''));
DealName = myform.DealName.value;
DealNo = myform.DealNo.value;
accom = parseFloat(myform.accom.value.replace(/\,/g,''));
freightmu = parseFloat(myform.freightmu.value.replace(/\,/g,''));
freightadj = parseFloat(myform.freightadj.value.replace(/\,/g,''));
premiums = parseFloat(myform.premiums.value.replace(/\,/g,''));
invadj = parseFloat(myform.invadj.value.replace(/\,/g,''));


Also, here is the table containing these fields. Thought it might help:


<table width="100%" border="0" cellspacing="0" cellpadding="1">
<tr>
<td align="right" valign="bottom" class="text">Your PPV Plan Commission Level&nbsp;</td>
<td align="left" valign="bottom">
<select name="tier">
<option value=A><font face="Arial, Helvetica, sans-serif">A </font>
<option value=B><font face="Arial, Helvetica, sans-serif">B </font>
<option value=C><font face="Arial, Helvetica, sans-serif">C </font>
</select>
</td>
<td valign="bottom" align="right" class="text">Deal Name&nbsp;</td>
<td valign="bottom" align="left" colspan="2" class="text">
<input type="text" name="DealName" id="DealName" size="40" value="(Optional)">
</td>
</tr>
<tr>
<td align="right" class="text" valign="bottom">Your ROVA Plan Commission Level&nbsp;</td>
<td align="left" valign="bottom">
<select name=level>
<option value=S><font face="Arial, Helvetica, sans-serif">Standard</font>
<option value=M><font face="Arial, Helvetica, sans-serif">Master,/font>
</select>
</td>
<td align="right" class="text" valign="bottom">Deal #&nbsp; </td>
<td align="left" valign="bottom">
<input type="text" name="DealNo" id="DealNo" value="(Optional)" size="8"></td>
<td align="left" valign="bottom">&nbsp;</td>
</tr>
<tr>
<td align="right" valign="bottom" class="text">Product Line&nbsp;</td>
<td valign="bottom" align="left" colspan="4">
<!---<select name="product" class="product" onchange="PopCategory(this.value);invoice.focus()">--->
<select name="product" class="product" onChange="PopCat();invoice.focus()">
<option><span class="product">SELECT PRODUCT</span>
<cfoutput query="GetProducts">
<option value="#Category#">#Description#</option>
</cfoutput>
</select>
<input type="hidden" name="display_product">
</td>
</tr>
<tr>
<td align="right" valign="bottom" class="text">Product Group&nbsp;</td>
<td align="left" valign="bottom" width="128">
<input type="text" align="right" id="category" name="category" size="15"></td>
<td align="right" valign="bottom" width="144" class="text">Client Accommodations&nbsp;</td>
<td align="left" valign="bottom" width="128">
<input type="text" align="right" id="accom" name="accom" onKeyUp="format(this)" onChange="format(this)" size="15" tabindex=5>
<font color="#FF0000"><b>* </b></font> </td>
<td align="left" valign="top" rowspan="2" class="redbold" width="282">* Do NOT leave blank: you MUST enter a number in EVERY field, even if it's a 0.</td>
</tr>
<tr>
<td align=right valign="bottom" class="text">Invoice Subtotal&nbsp; </td>
<td align="left" valign="bottom">
<input type="text" align="right" size="15" id="invoice" name="invoice" onKeyUp="format(this)" onChange="format(this)" tabindex=1>
<font color="#FF0000"><b>* </b></font> </td>
<td align="right" valign="bottom" class="text">Freight Mark-up&nbsp;</td>
<td align="left" valign="bottom">
<input type="text" align="right" id="freightmu" name="freightmu" onKeyUp="format(this)" onChange="format(this)" size="15" tabindex=6>
<font color="#FF0000"><b>* </b></font> </td>
</tr>
<tr>
<td align="right" valign="bottom" class="text">Cost of Materials&nbsp;</td>
<td align="left" valign="bottom">
<input type="text" align="right" id="materials" name="materials" onKeyUp="format(this)" onChange="format(this)" size="15" tabindex=2>
<font color="#FF0000"><b> * </b></font> </td>
<td align="right" valign="bottom" class="text">Freight Adjustments&nbsp;</td>
<td align="left" valign="bottom">
<input type="text" align="right" id="freightadj" name="freightadj" onKeyUp="format(this)" onChange="format(this)" size="15" tabindex=7>
<font color="#FF0000"><b>* </b></font> </td>
<td align="center" valign="top" rowspan="2">
<table width="160" border="1" cellspacing="0" cellpadding="0" bordercolor="#FF0000" height="30">
<tr>
<td>
<table width="100%" cellspacing="0" cellpadding="2" align="center" height="24">
<tr>
<td align="center" width="81">
<input type=button value="Calculate." name="Calculate" onClick="calculate(this.form)">
</td>
<td align="center" width="61">
<input type=reset value="Reset." name="Reset">
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align=right valign="bottom" class="text">Cost of Manufacturing&nbsp;</td>
<td align=left valign="bottom">
<input type=text align="right" id="mfg" name="mfg" onKeyUp="format(this)" onChange="format(this)" size="15" tabindex=3>
<font color="#FF0000"><b> * </b></font> </td>
<td align="right" valign="bottom" class="text">Sales Premiums&nbsp;</td>
<td align=left valign="bottom">
<input type="text" align="right" id="premiums" name="premiums" onKeyUp="format(this)" onChange="format(this)" size="15" tabindex=8>
<font color="#FF0000"><b>* </b></font> </td>
</tr>
<tr>
<td align=right class="text" valign="top">PPV List Price&nbsp; </td>
<td align="left" valign="top">
<input type="text" align="right" id="ppvlist" name="ppvlist" onKeyUp="format(this)" onChange="format(this)" size="15" tabindex=4>
<font color="#FF0000"><b> * </b></font></td>
<td align="right" class="text" valign="top">Invoice Adjustments&nbsp;</td>
<td align="left" valign="top">
<input type="text" align="right" id="invadj" name="invadj" onKeyUp="format(this)" onChange="format(this)" size="15" tabindex=9>
<font color="#FF0000"><b>* </b></font> </td>
<td align="center" valign="bottom">
<table width="120" border="1" cellspacing="0" cellpadding="0" bordercolor="#FF0000" height="30">
<tr>
<td>
<table width="100%" cellspacing="0" cellpadding="2" height="24" align="center" valign="middle">
<tr>
<td align="center" valign="middle">
<input type="submit" name="Excel" value="Export to Excel">
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>


Let me know if you need anything else from me in order to look into this.
As I said before, I am only a beginner, and can use all the help I can get. I'm really stuck on this one. :confused:

Thanks!

Willy Duitt
05-26-2005, 03:18 AM
Here's another version I found in my archives from last September which by its file name I expect that it accepts negative numbers...



<script type="text/javascript">
function format(input){
var num = input.value.replace(/\,/g,'');
// if(!isNaN(num)){
if(num.indexOf('.') > -1){
num = num.split('.');
num[0] = num[0].toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'');
if(num[1].length > 2){
alert('You may only enter two decimals!');
num[1] = num[1].substring(0,num[1].length-1);
} input.value = num[0]+'.'+num[1];
} else{ input.value = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^(\-)?\,/,'$1') };
// }

// else{
// var temp = input.value;
// alert('You may enter only numbers in this field!');
// input.value = temp.replace(/[^\d\.]*/g,'');
// }
}
</script>
</head>

<body>
<form name="calculator" method="post" action=""
onsubmit="this.input.value=this.input.value.replace(/\,/g,'')">
<input type="text" name="input" onkeyup="format(this)" onchange="format(this)"
onblur="if(this.value.indexOf('.')==-1)this.value=this.value+'.00'">
<input type="submit" value="Submit">
</form>


.....Willy



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum