JavaScript - Number Format Add Commas?
Is there a built in function to format a number to 2 decimal places and to add commas like below.
2,222.33 30,033.98 1,222,345,99 Similar TutorialsI frequent a site that involves typing huge numbers. And I'm thinking of making a userscript that automatically adds commas as I type numbers on all the input boxes. There are multiple input boxes and it has two types: First input type has similar name ; Second input type has similar class. Here's an example of a page: Code: <input type="text" value="0" name="buy_price"><br/> <input type="text" value="0" name="buy_price"><br/> <input type="text" value="0" name="buy_price"><br/> <br/> <input type="text" value="0" class="money-input"><br/> <input type="text" value="0" class="money-input"><br/> <input type="text" value="0" class="money-input"> My code so far. But it doesn't seem to work. The main function was taken from here. Code: function add_commas(number){ //remove any existing commas... number=number.replace(/,/g, ""); //start putting in new commas... number = '' + number; if (number.length > 3) { var mod = number.length % 3; var output = (mod > 0 ? (number.substring(0,mod)) : ''); for (i=0 ; i < Math.floor(number.length / 3); i++) { if ((mod == 0) && (i == 0)) output += number.substring(mod+ 3 * i, mod + 3 * i + 3); else output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3); } return (output); } else return number; } function addattribute() { //adds onkeyup and removes zero of first input type document.getElementsByName("buy_price")[0].setAttribute("onkeyup", "this.value=add_commas(this.value);"); document.getElementsByName("buy_price")[0].removeAttribute('value'); //adds onkeyup and removes zero of second input type document.getElementsByClassName("money-input")[0].setAttribute("onkeyup", "this.value=add_commas(this.value);"); document.getElementsByClassName("money-input")[0].removeAttribute('value'); } window.onload = addattribute; EDIT: I believe the function function add_commas(number) works. But the problem is I need to find a way to add onkeyup="this.value=add_commas(this.value);" to the input boxes mentioned. EDIT #2: Well I guess I'm back to 0.The function function add_commas(number) seems to only work if it's on the actual html file inside <script> tags. But once you separate it and apply it as a userscript, it doesn't seem to function. I'm not too sure how to approach this but I have a date input that uses a jQuery pop-up for a calendar, and enters the date in a format d MMM yy (1 Jan 11). Not everyone wants to be clicking and choosing the date from the calendar but to be entering it just as a number such as 0101, 010111 or 01012011 which can be faster. This would then need to be converted to the d MMM yy format as per the jQuery pop-up when they exit the input box. So really only if it's a number format it needs to look at the number of digits... and does the conversion. Has anyone done something like this before? Or is there a link to how I could go about achieving this? Many thanks David Hi Guys, I'm looking for a way to convert a number in to currency format so 10000000 is 10,000,000 etc... i found this code and was hoping someone could advise how to tweak it so that it works automatically without having to hit a button i.e. I will be passing a value dynamically to the code and want it evaluated without the user clicking anything if the code was like var="10000000" <-the number I dynamically pass in and output 10,000,000 You probably guessed Javascript aint my forte. Thanks http://www.designerwiz.com/JavaScrip...ncy_format.htm Code: <!-- // == This Script Free To Use Providing This Notice Remains == // // == This Script Has Been Found In The http://www.DesignerWiz.com Javascript Public Archive Library == // // == NOTICE: Though This Material May Have Been In A Public Depository, Certain Author Copyright Restrictions May Apply == // --><script language="JavaScript" type="text/javascript"> <!-- Begin function checkNum(data) { // checks if all characters var valid = "0123456789."; // are valid numbers or a "." var ok = 1; var checktemp; for (var i=0; i<data.length; i++) { checktemp = "" + data.substring(i, i+1); if (valid.indexOf(checktemp) == "-1") return 0; } return 1; } function dollarAmount(form, field) { // idea by David Turley Num = "" + eval("document." + form + "." + field + ".value"); dec = Num.indexOf("."); end = ((dec > -1) ? "" + Num.substring(dec,Num.length) : ".00"); Num = "" + parseInt(Num); var temp1 = ""; var temp2 = ""; if (checkNum(Num) == 0) { alert("This does not appear to be a valid number. Please try again."); } else { if (end.length == 2) end += "0"; if (end.length == 1) end += "00"; if (end == "") end += ".00"; var count = 0; for (var k = Num.length-1; k >= 0; k--) { var oneChar = Num.charAt(k); if (count == 3) { temp1 += ","; temp1 += oneChar; count = 1; continue; } else { temp1 += oneChar; count ++; } } for (var k = temp1.length-1; k >= 0; k--) { var oneChar = temp1.charAt(k); temp2 += oneChar; } temp2 = "$" + temp2 + end; eval("document." + form + "." + field + ".value = '" + temp2 + "';"); } } // End --></script> <center> <form name=commaform>Enter a number then click the button: <input type=text name=input size=10 value=""> <input type=button value="Convert" onclick="dollarAmount(this.form.name, 'input')"> <br><br> or enter a number and click another field: <input type=text name=input2 size=10 value="" onBlur="dollarAmount(this.form.name, this.name)"> </form> Does anyone know of a good library/function that will add the commas to a number automatically as the number is entered into a field?
Hello: I have an expression validating email addresses but it seems there is a loophole. If a user enters a comma this is accepted. Can anyone tell me how i can modify the following to disallow commas? validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i; strEmail = document.form1.df_email1.value; if (strEmail.search(validRegExp) == -1) { alert("A valid e-mail address is required."); document.form1.df_email1.focus(); return false; } Hello my first post. I have a function that insert commas via onclick or onblur. Code: function addCommas(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } I also am using code from this link, where I can specify what parameters to allow the user to enter only positive/negative, decimals values and restricting characters that are not allowed. http://www.mredkj.com/tutorials/validate2.html I am having a hard time to incorporate the addCommas function into the link above. Does anyone have an example that I can look at where I can have commas added to a value dynamically while typing? e.g. if I type 1000 after that last 0 keystroke, it turns the value into 1,000. If I add 3 more zeros it turns it into 1,000,000. In the same vain if I subtract a 0 from the 1,000,000 the value is 100,000 instead. I appreciate any assistance in advance. Hi All, Using Dreamweaver CS4. I have a web form that is submitted and then we pull up the information in excel using delimited fields. The problem with this is the end user will use commas (even though we have messages that say do not use commas) which messes up our data in excel. I created some code for a different field where commas were more frequent but there are new fields that users are adding commas into. Anyways, I can't figure out exactly how to code this and was wondering if someone could work out the kinks for me: My code: Code: if ( trim( frm.elements["ShipToBuildingRoom."] ).length < 4 ) oops += "You must enter your Building and Room information.\n"<br> var val = frm.ShipToBuildingRoom.value.replace(/[^\d\;\,]/g, "" ).replace(/\,/g, ";"); frm.ShipToBuildingRoom.value = val; I have a function below where every time a question is submitted, it will add a new row in the table with a textbox which allows numbers entry only. My question is that I don't know how to code these features in this function: 1: I want the text box to be between 0 and 100, so if text box contains a number which is above 100, it will automatically change the number to the maximum number which is 100. Does any one know how to code this in my function below in javascript: Code: function insertQuestion(form) { var row = document.createElement("tr"); var cell, input; cell = document.createElement("td"); cell.className = "weight"; input = document.createElement("input"); input.name = "weight_" + qnum; input.onkeypress = "return isNumberKey(event)"; cell.appendChild(input); row.appendChild(cell); } When I used toFixed() method on a number, I thought that this method round a number to a specified approximation, but I got a surprising result, the number became string! 15.23689 .toFixed ( 2 ) ==> "15.24" So does it convert the number into string? I am trying to figure out how to make a random number I can plug into a script count down from that number at certain times of the day until it reaches 0. I would like it to reset itself at midnight every day. I'm trying to make it work with a script I found on here that resets itself at midnight every day. So instead of it counting down too fast, it would count down to the next number after a randomly generated number of minutes until it reaches 0. But it wouldn't necessarily have to end at 0 at midnight. It could go from 845 to 323 at the end of the day at a slower pace. Is that possible?
I came across this really interesting experiment. http://www.romancortes.com/blog/a-tr...o-the-beatles/ What I was wondering was does anyone know what the data used is from? I mean what type of image format it is. I've tried to figure it out but I just can't find what it is. I see how the script works, but I was wondering if the author used some available image format or if he created the image data from scratch. Thanks for any advice you might be able to offer. i try to create a simple editor. But i'm having problem with bullets hierarchy Code: <html> <body> <style type="text/css"> #preview,#editor,#editor-html{ width:500px; height:250px;} #preview{ clear:both;background:#eee; } #editor,#editor-html{ float:left;} </style> <div id="preview"></div> <p><textarea id="editor" ></textarea></p> <p><textarea id="editor-html"></textarea></p> <script type="text/javascript"> var oEdit = document.getElementById('editor'); var oCheck = document.getElementById('editor-html'); var oPrev = document.getElementById('preview'); function doBullets(s){ var s = this.value; var r = /\n{2}\s#\s[\s\S.]*?\n{2}/g; var a = s.match(r); var step = 0; var bCount = false; if(a){ a = a.toString(); a = a.split(/\n{2}/g); var iL = 0; var iMax = 0; for(var j=0;j<a.length;j++){ if(a[j].match(/^\s#\s/)){ var iF = s.indexOf(a[j]); var iL = a[j].length; var html = ''; var list = a[j].split(/\s#/); for(var i=0;i<list.length;i++){ if(list[i]){ var level = list[i].match(/^\s?#*\s/); level = level?(level[0].length):0; var txt = list[i].replace(/^\s?#*\s/,'').toString().replace(/\n?$/,''); if(level > step){ step++; iMax++; html = html.replace(/<\/li>\n?$/,''); html += '\n<ul>\n'; } if(level < step){ step--; html += '</ul>\n'; } var iCounter = iMax-level; if(iCounter){ for(var y=0;y<iCounter-1;y++){ html += '</li></ul></li>'; } } document.title = level+' '+step+' '+iMax+' counter:'+iCounter; html += '<li>'+txt+'</li>\n'; } } s = s.substring(0,iF)+html+s.substring(iF+iL,s.length); } } } oPrev.innerHTML = s; oCheck.value = s; } oEdit.onkeyup = doBullets; </script> </body> </html> Please help... 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 We format euro currency as 1.000.000,00 (just the opposite of USD). Anyone who could give me a script that changes the input into this format? I tried 'replace' with a regular expression, but my regexes don't work. I am trying to get my script working in FF, IE and Opera but the getAttribute isn't working for me. The domain name isn't getting picked up I have tried this: var dom_name = document.getElementById('dom_nm').getAttribute("value",2); and this: var dom_name = document.getElementById('dom_nm').getAttribute('value'); After this I use the domain name like this: Code: if (per2 == 0) { item_desc = "Domain Name and DNS set up. Domain: "+dom_name+" Period: "+per1+"year"+" No Privacy."; } if (per2 > 0){ item_desc = "Domain Name and DNS set up. Domain: "+dom_name+" Period: "+per1+"year"+" Including: Privacy: "+per2+"year."; } document.getElementById('item_pay').setAttribute("value","item_desc"); ( I also tried: Code: document.getElementById('item_pay').setAttribute('value') = item_desc; but that didn't seem to work either ) The HTML is like this: Code: <div style="margin: 5px auto;"> <table> <th>Your New Domain Name Order</th> <tr><td>Product</td><td>Cost</td><td>Years (max. 10)</td><td style="text-align: right;">Total Cost</td></tr> <tr><td id="dom_nm" value="John.Doe"><?php echo "Domain: $N_dom.$N_tld" ?></td><td id="price" value = '<?php echo "$priceN" ?>' ><?php echo $priceN ?></td><td><input style="background-color: yellow; font-weight: bold;" type='TEXT' id="per_1" size = '10' value = '<?php echo "$period_1" ?>' ></td><td><input type='TEXT' id="total_1" style="text-align: right;" value = '<?php echo "$total_1" ?>'></td></tr> <tr><td>Domain Privacy</td><td>8.70</td><td><input style="background-color: yellow; font-weight: bold;" type='TEXT' id="per_2" size = '10' value = '<?php echo "$period_2" ?>'></td><td><input type='TEXT' id="total_2" style="text-align: right;" value = '<?php echo "$total_2" ?>'></td></tr> <tr><td>Total Order.</td><td> --- </td><td> --- </td><td><input type='TEXT' id="total_3" style="text-align: right; font-weight: bold;" value = '<?php echo "$total_3" ?>'></td></tr> </table> </div> The result is that I get a zero ( 0 ) where the domain should be. Like this: Domain Name and DNS set up. Domain: 0 Period: 2year Including: Privacy: 2year. Plus Free Blog Install. Any ideas what I am doing wrong ? Thanks hey all - new to the forum, and need some quick help. i have a form with multiple data entry fields, one of which i need to be in a certain format. currently it will only check for total length (17 digits), which is part of it, but the format needs to be exactly: 0000-00000-000000 (where zeros are numbers) the best thing would be if when the user enters 15 digits, it would automatically format it with the dashes. any and all help is appreciated. please note: this is being used for a print solutions software that auto-generates most of the code, we cannot rewrite all of the code, only work with what we have. here is the code: Code: if (Form1.elements['EIF2']){ if(Form1.elements['EIF2'].disabled == false){ if (!CheckEntry('EIF2', 'Lawson # ', true, 17, 'exactly'))return false; } Hello! First of all, sorry my bad english. (and javascripting skills...) I have a problem with date formatting! My code is supposed to get the day of the week from date format like dd.mm.yyyy (01.01.2010, 31.12.2010) but it only works if date format is like "28 December, 2000". Code is he Code: <script type="text/javascript"> function getTheDay(aText) { myDays=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] myDate=new Date(eval('"'+aText.value+'"')) document.form1.textDay.value=myDays[myDate.getDay()] } </script> <form name="form1" id="form1" method="post" action="" enctype="text/plain"> <input type="text" name="textDate" id="textDate" value="" size="25" onchange="getTheDay(this.form.textDate)" /> <br /> <input type="text" name="textDay" size="25" maxlength="25" /> </form> Original code: http://www.trans4mind.com/personal_d...ript/time2.htm Can anyone help me? I have tried everything what i have find from google... Thanks to you all who help me with this! -Roosterr Alright so I've been searching around trying to figure out how to change the date format, the way I have seen it the most is like Code: var d=new Date(); var datestring=d.getdate + d.getMonth + d.get Year I am new to javascript and this is the first script I have written on my own so this is what it does. It is supposed to display the date that a shipment should arrive on with 2 day shipping through ups so it skips weekends. It displays the date after either adding 2 days or more depending on the day of the week. But the way the date is formatted really needs to be changed. So if any one can suggest maybe how to tie in the above code with mine that would be great. Code: <script type="text/javascript"> var d=new Date(); var day=d.getDay(); if (day <= 3){ d.setDate (d.getDate() + 2); } else if (day == 4) { d.setDate (d.getDate() + 4) } else if (day == 5){ d.setDate (d.getDate() + 4); } else if (day == 6) { d.setDate (d.getDate() + 3); } document.write("Your card should arrive on " + d); </script> Hi, I have a textarea element and I fill it with text. But I want to insert newlines to seperate some of the words in the textarea. I tried to use '\r' or '\n' or '\r\n', but none of them works. Code: var textArea = document.createElement('textarea'); textArea.value = 'good' + '\n' + 'morning'; The newline has no effect, it still show 'good morning'. Why? And also, I am going to write these words in the textarea into database and later retrieve them back from database to another textarea, should I keep the newline characters or is it better use some other delimiter? Many thanks. Hello. I have got this kind of array: Code: $days = array('Monday' => '2012-03-19', 'Tuesday' => '2012-03-20' ); I'm iterating like this: Code: foreach($days as $key => $value){ echo '<a href="javascipt:confirmDelete('.$value.');">Delete</a>'; } Script: Code: function confirmDelete(day) { if (confirm('Delete?')) { window.location.href = 'processDay.php?action=delete&day=' + day ; } } While i hover over the link with coursor, it show it good: javascript:confirmDelete(2012-03-19), but when I submit the delete confirmation, i get &day=1987. Where is the problem? |