Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    Regular Coder
    Join Date
    Oct 2011
    Posts
    116
    Thanks
    19
    Thanked 1 Time in 1 Post

    Numeric Textbox with format

    Dear Experts

    I have following codes

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
       "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <meta name="language" content="english"> 
    <meta http-equiv="Content-Style-Type" content="text/css">
    
    <title>Numeric Textbox Sample</title>
    
    <style type="text/css">
    #box1	{width:200px;height:170px;border:1px solid green;background:#e3eeff;padding-top:20px;}
    
    .button	{width:100px;margin-top:0px;}
    
    body {
        margin:0;
    margin-top:100px;
    	 }
    </style>
    
    <script language="javascript">
    
    function NumericDotOnly()
    {
    var key = window.event.keyCode; 
    
    if (((key >47) && (key <58)) || (key==46))
    window.event.returnValue = true;
    else 
    window.event.returnValue = false;
    }
    
    function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + num + '.' + cents);
    }
    
    
    </script>
    
    </head>
    
    <body onload="form2.text1.focus()" >
    <center>
    <p>I need following format<br>
    99,999,999.99<br>
    </p>
    <div id="box1">
    		<form name=form2>
    		<table width="100%" border="0" cellpadding="0" cellspacing="0">
    		<tr><td>Amount</td> 
    
    <td><input type=text name=text1 size=15 value="" onkeypress="NumericDotOnly
    
    ()";onblur="formatCurrency(this.value)"> </td></tr>	
    
    	<tr><td>Tax</td> <td><input type=text name=text2 size=15 value="" 
    
    onkeypress="NumericDotOnly()";onblur="formatCurrency(this.value)"></td></tr>		
    <tr><td>Result</td><td><input type=text name=text3 size=15 value="" disabled></td></tr>
    
    		</table>
    		<hr>
    		<input class="button" type=button name=command1 value="Plus" 
    
    onclick="form2.text3.value=parseFloat(form2.text1.value)+parseFloat(form2.text2.value)"><br>
    
    		<input class="button" type=button name=command8 value="Focus" 
    
    onclick="form2.text1.select()";"form2.text1.focus()"><br>
    		<input class="button" type=reset name=command9 value="Reset">
    	
    </form>
    </div>
    
    </center>
    </body>
    </html>
    Please help me to apply following format

    99,999,999.99

    Thanks in advance

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,245
    Thanks
    203
    Thanked 2,555 Times in 2,533 Posts
    Here you are:-

    Code:
    <script type = "text/javascript">
    
    function addCommas(nStr) {
    nStr = nStr.replace(/[^0-9\.]/g,"");
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
    nStr = nStr.replace(rgx, '$1,$2');
    }
    nStr = "$" + nStr; // if $ prefix required
    if (nStr.indexOf('.') == -1) {  // if whole number add .00
    nStr = nStr + ".00";
    }
    nStr = nStr.replace(/(\.\d)$/,"$10");  // if only one DP add another 0
    return nStr;
    }
    
    alert (addCommas("999999999.99"));
    </script>

    Before a man speaks it is safe to assume that he is a fool. After he speaks it is seldom necessary to assume. - H.L. Mencken 1880-1956, American Editor, Author, Critic, Humorist

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #3
    Senior Coder chump2877's Avatar
    Join Date
    Dec 2004
    Location
    the U.S. of freakin' A.
    Posts
    2,838
    Thanks
    21
    Thanked 157 Times in 148 Posts
    I think this is more or less what you are after (only tested in Firefox):

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
       "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    	<meta name="language" content="english">
    	<meta http-equiv="Content-Style-Type" content="text/css">
    	<title>Numeric Textbox Sample</title>
    	<style type="text/css">
    		#box1	{width:200px;height:170px;border:1px solid green;background:#e3eeff;padding-top:20px;}
    		.button	{width:100px;margin-top:0px;}
    		body {margin:0;margin-top:100px;}
    	</style>
    	<script type="text/javascript">
    		var amount = '';
    		var tax = '';
    
    		function NumericDotOnly(inputObj, e)
    		{
    			var isAmount = inputObj.id == "amountVal";
    			var e = (!e) ? window.event : e;
    			var key = e.keyCode;
    			if ((key < 48 || key > 57) && key != 8 && key != 110 && key != 190 || ((key == 110 || key == 190) && ((isAmount) ? amount : tax).indexOf('.') != -1))
    			{
    				inputObj.value = (isAmount) ? amount : tax;
    			}
    
    			if (isAmount)
    			{
    				amount = inputObj.value;
    			}
    			else
    			{
    				tax = inputObj.value;
    			}
    		}
    
    		function formatCurrency(inputObj)
    		{
    			if (inputObj.id == "amountVal")
    			{
    				amount = convertToFloat(inputObj.value);
    			}
    			else
    			{
    				tax = convertToFloat(inputObj.value);
    			}
    			inputObj.value = (inputObj.value != '') ? addCommas(convertToFloat(inputObj.value)) : '';
    		}
    
    		function convertToFloat(num)
    		{
    			return (num != '') ? parseFloat(num.replace(/,/g, "")).toFixed(2) : num;
    		}
    
    		function addCommas(num)
    		{
    			var numParts = num.split('.');
    			var numArr = numParts[0].split('').reverse();
    			var newArr = [];
    			var count = -1;
    			for (var i=0; i<numArr.length; i++)
    			{
    				if (i % 3 == 0)
    				{
    					newArr[++count] = ',';
    				}
    				newArr[++count] = numArr[i];
    			}
    			return newArr.reverse().join('').replace(/((.+?)(,?))$/, '$2') + '.' + numParts[1];
    		}
    
    		function findSum()
    		{
    			document.form2.text3.value = (document.form2.text1.value != '' && document.form2.text2.value != '') ? addCommas((parseFloat(document.form2.text1.value.replace(/,/g, "")) + parseFloat(document.form2.text2.value.replace(/,/g, ""))).toFixed(2)) : '';
    		}
    
    		function giveFocus()
    		{
    			document.form2.text1.select();
    			document.form2.text1.focus();
    		}
    
    		window.onload = giveFocus;
    	</script>
    </head>
    <body>
    <center>
    	<p>I need following format<br>
    	99,999,999.99<br>
    	</p>
    	<div id="box1">
    		<form name=form2>
    			<table width="100%" border="0" cellpadding="0" cellspacing="0">
    				<tr>
    					<td>Amount</td>
    					<td><input id="amountVal" type="text" name="text1" size="15" value="" onkeyup="NumericDotOnly(this, event)" onblur="formatCurrency(this)" onfocus="this.value = amount" /></td>
    				</tr>
    				<tr>
    					<td>Tax</td>
    					<td><input type="text" id="taxVal" name="text2" size="15" value="" onkeyup="NumericDotOnly(this, event)" onblur="formatCurrency(this)" onfocus="this.value = tax" /></td>
    				</tr>
    				<tr>
    					<td>Result</td>
    					<td><input type="text" name="text3" size="15" value="" disabled="disabled" /></td>
    				</tr>
    			</table>
    			<hr>
    			<input class="button" type="button" name="command1" value="Plus" onclick="findSum()" /><br>
    			<input class="button" type="button" name="command8" value="Focus" onclick="giveFocus()" /><br>
    			<input class="button" type="reset" name="command9" value="Reset" />
    		</form>
    	</div>
    </center>
    </body>
    </html>
    Regards, R.J.

    ---------------------------------------------------------

    Help spread the word! Like my YouTube-to-Mp3 Conversion Script on Facebook !! :-)
    [Related videos and tutorials are also available at my YouTube channel and on Dailymotion]
    Get free updates about new software version releases, features, and bug fixes!
    ♪♪ …Need Web Hosting For My YouTube-To-Mp3 Conversion Software? Check Here !!… ♪♪

  • Users who have thanked chump2877 for this post:

    tqmd1 (12-24-2011)

  • #4
    Regular Coder
    Join Date
    Oct 2011
    Posts
    116
    Thanks
    19
    Thanked 1 Time in 1 Post
    Dear Sir chump2877,

    Thanks for helping, when I run your codes then nothing is entered in any of textboxes. Cursor moves at start position.

    Here are your codes

    Code:
    <td><input id="amountVal" type="text" name="text1" size="15" value="" onkeyup="NumericDotOnly(this, event)" onblur="formatCurrency(this)" onfocus="this.value = amount" /></td>
    I modify it as

    Code:
    <td><input id="amountVal" type="text" name="text1" size="15" value=""  onblur="formatCurrency(this)" onfocus="this.value = amount" /></td>
    Removed this codes from your codes

    Code:
    onkeyup="NumericDotOnly(this, event)"
    Now data is entered into textboxes including character data

    Please modify your codes to accept only numeric type of data

    Thanks

  • #5
    Senior Coder chump2877's Avatar
    Join Date
    Dec 2004
    Location
    the U.S. of freakin' A.
    Posts
    2,838
    Thanks
    21
    Thanked 157 Times in 148 Posts
    when I run your codes then nothing is entered in any of textboxes. Cursor moves at start position.
    I dont understand what you are saying here.

    Removed this codes from your codes
    Why would you remove this code?

    Now data is entered into textboxes including character data

    Please modify your codes to accept only numeric type of data
    When you removed a portion of my code, you removed the capability to essentially validate characters (as numeric) as they are typed into the text boxes. Put the code back in and it will work correctly.
    Regards, R.J.

    ---------------------------------------------------------

    Help spread the word! Like my YouTube-to-Mp3 Conversion Script on Facebook !! :-)
    [Related videos and tutorials are also available at my YouTube channel and on Dailymotion]
    Get free updates about new software version releases, features, and bug fixes!
    ♪♪ …Need Web Hosting For My YouTube-To-Mp3 Conversion Software? Check Here !!… ♪♪

  • #6
    Regular Coder
    Join Date
    Oct 2011
    Posts
    116
    Thanks
    19
    Thanked 1 Time in 1 Post
    Sir,

    Simply copy your code into aaa.html and run.
    You will see textboxes are not accepting any type of data.

    When I try to enter any data then control moves to at beginning position.

    Wish you good luck

  • #7
    Senior Coder chump2877's Avatar
    Join Date
    Dec 2004
    Location
    the U.S. of freakin' A.
    Posts
    2,838
    Thanks
    21
    Thanked 157 Times in 148 Posts
    What browser are you using? I have just tested my code in the latest versions of Firefox, IE, Opera, and Chrome, and it works fine in all of them.
    Regards, R.J.

    ---------------------------------------------------------

    Help spread the word! Like my YouTube-to-Mp3 Conversion Script on Facebook !! :-)
    [Related videos and tutorials are also available at my YouTube channel and on Dailymotion]
    Get free updates about new software version releases, features, and bug fixes!
    ♪♪ …Need Web Hosting For My YouTube-To-Mp3 Conversion Software? Check Here !!… ♪♪

  • #8
    Regular Coder
    Join Date
    Oct 2011
    Posts
    116
    Thanks
    19
    Thanked 1 Time in 1 Post
    Sir I am using Internet Explorer 8.
    I have tested again but the problem is still exists.

  • #9
    Senior Coder chump2877's Avatar
    Join Date
    Dec 2004
    Location
    the U.S. of freakin' A.
    Posts
    2,838
    Thanks
    21
    Thanked 157 Times in 148 Posts
    Just tested in IE8 and it works there as well...Are you sure you have your browser configured to allow JS to run from local files (Intranet settings)? You will have to do that until you can upload the script to an actual web server.

    Edit:
    And you HAVE TO use the original code that I posted in this thread. Do NOT use the version of the code that you have recently modified.
    Last edited by chump2877; 12-24-2011 at 08:56 AM.
    Regards, R.J.

    ---------------------------------------------------------

    Help spread the word! Like my YouTube-to-Mp3 Conversion Script on Facebook !! :-)
    [Related videos and tutorials are also available at my YouTube channel and on Dailymotion]
    Get free updates about new software version releases, features, and bug fixes!
    ♪♪ …Need Web Hosting For My YouTube-To-Mp3 Conversion Software? Check Here !!… ♪♪

  • #10
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,245
    Thanks
    203
    Thanked 2,555 Times in 2,533 Posts
    To answer the question you sent by PM , you cannot add numbers which have been converted to strings by adding commas. You need to retain these in numeric form.

    Here you are:-

    Code:
    <html>
    <head>
    <script type = "text/javascript">
    
    function addCommas(nStr) {
    nStr = nStr.replace(/[^0-9\.]/g,"");
    nStr = Number(nStr).toFixed(2);   // remove excess decimals
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
    nStr = nStr.replace(rgx, '$1,$2');
    }
    if (nStr.indexOf('.') == -1) {  // if whole number add .00
    nStr = nStr + ".00";
    }
    nStr = nStr.replace(/(\.\d)$/,"$10");  // if only one DP add another 0
    return nStr;
    }
    
    var x1;
    var x2;
    
    function show() {
    var totalStr = (x1 + x2).toString();
    totalStr = addCommas(totalStr);
    document.form1.text3.value = totalStr;
    }
    
    </script>
    
    <head>
    <body>
    <center>
    <form name ="form1">
    <input type=text name=text1 size=15 value="" onblur="x1 = Number(this.value) || 0; this.value=addCommas(this.value)"><br>
    <input type=text name=text2 size=15 value="" onblur="x2 = Number(this.value) || 0; this.value=addCommas(this.value)"><br>
    <input type=text name=text3 size=15 value="" disabled><br>
    <input type=button value="Show" onclick="setTimeout(show,10)">
    </form>
    </center>
    </body>
    </html>
    Last edited by Philip M; 12-24-2011 at 12:48 PM. Reason: Improved

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #11
    Regular Coder
    Join Date
    Oct 2011
    Posts
    116
    Thanks
    19
    Thanked 1 Time in 1 Post
    Sir Philip M,

    According to your codes.

    When I press SHOW button it displays correct answer.

    But....

    When I change values into both textboxes and again press SHOW button

    Then...

    It displays .00 instead of correct answer.

    Please review while changing values of textboxes.

  • #12
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,245
    Thanks
    203
    Thanked 2,555 Times in 2,533 Posts
    Quote Originally Posted by tqmd1 View Post
    Sir Philip M,

    According to your codes.

    When I press SHOW button it displays correct answer.

    But....

    When I change values into both textboxes and again press SHOW button

    Then...

    It displays .00 instead of correct answer.

    Please review while changing values of textboxes.
    You are trying to edit "numbers" which have already been formatted into strings with commas. If the user wishes to change the value entered he must re-enter the new value completely.

    Code:
    <input type=text name=text1 size=15 value="" onfocus = 'this.value = "" ' ; onblur="x1 = Number(this.value); this.value=addCommas(this.value)"><br>
    <input type=text name=text2 size=15 value="" onfocus = 'this.value = "" '; onblur="x2 = Number(this.value); this.value=addCommas(this.value)"><br>
    Last edited by Philip M; 12-24-2011 at 11:11 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    tqmd1 (12-24-2011)

  • #13
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,245
    Thanks
    203
    Thanked 2,555 Times in 2,533 Posts
    Here is an improved version which truncates excess decimal places (so 2.999 is truncated to 2.99 and not rounded to 3.00) rather than rounds them, which may give rise to apparant errors:-


    Code:
    <html>
    <head>
    <script type = "text/javascript">
    
    function addCommas(nStr) { 
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
    nStr = nStr.replace(rgx, '$1,$2');
    }
    if (nStr.indexOf('.') == -1) {  // if whole number add .00
    nStr = nStr + ".00";
    }
    nStr = nStr.replace(/(\.\d)$/,"$10");  // if only one DP add another 
    return nStr;
    }
    
    var x1;
    var x2;
    
    function show() {
    var totalStr = ((x1*1) + (x2*1)).toString();
    totalStr = addCommas(totalStr);
    document.form1.text3.value = totalStr;
    }
    
    function truncate(x) {  // truncate to 2DP
    x = x.replace(/[^0-9\.]/g,"");
    x = x *100;
    if (x < 0) {
    x = Math.ceil(x)/100;
    return x.toString();
    }
    else {
    x =  Math.floor(x)/100;
    return x.toString();
    }
    }
    
    </script>
    
    <head>
    <body>
    <center>
    <form name ="form1">
    <input type=text name=text1 size=15 value="" onfocus = 'this.value = "" ' ; onblur="x1 = truncate(this.value) || 0; this.value=addCommas(x1)"><br>
    <input type=text name=text2 size=15 value="" onfocus = 'this.value = "" ';  onblur="x2 = truncate(this.value) || 0; this.value=addCommas(x2)"><br>
    <input type=text name=text3 size=15 value="" disabled><br>
    <input type=button value="Show" onclick="setTimeout(show,25)">
    </form>
    </center>
    </body>
    </html>

    Note: the <center> tag is deprecated and you should use CSS styling to position page elements.
    Last edited by Philip M; 12-24-2011 at 01:45 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #14
    Regular Coder
    Join Date
    Oct 2011
    Posts
    116
    Thanks
    19
    Thanked 1 Time in 1 Post
    Sir, you codes work fine but I want to ask you
    is there any way to remove this line of code

    onfocus = 'this.value = ""

    If user moves cursor accross textboxes then values in textboxes are removed then he has to enter value again.

    If user edits value and press show button then it must accept new values for calculation.
    Last edited by tqmd1; 12-26-2011 at 06:24 AM.

  • #15
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,245
    Thanks
    203
    Thanked 2,555 Times in 2,533 Posts
    Quote Originally Posted by tqmd1 View Post
    Sir, you codes work fine but I want to ask you
    is there any way to remove this line of code

    onfocus = 'this.value = ""

    If user moves cursor accross textboxes then values in textboxes are removed then he has to enter value again.

    If user edits value and press show button then it must accept new values for calculation.
    I thought I had explained, you cannot edit the values after they have been formatted with commas as you desire.
    It is not a case of the user "moving the cursor over the textbox". The user must click on it for focus to be placed there.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •