I have a input field for user to input number. This number will be displayed in span tag as user is typing. And i would like to format this number in span tag with thousand separator.
Currently, it only show exactly what is typing without thousand separator:
JSFiddle
Here is my simplified code:
<!DOCTYPE html>
<html>
<head>
<script>
function charPreview(){
var x = document.getElementById("frm_price").value;
document.getElementById("frm_price_preview").innerHTML = x;
}
</script>
</head>
<body>
<form>
Price: <input type='text' id='frm_price'
onkeyup="charPreview()">
<span id="frm_price_preview"></span>
</form>
</body>
</html>
function charPreview(){
var x = document.getElementById("frm_price").value;
document.getElementById("frm_price_preview").innerHTML = decimalWithCommas(x);
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function decimalWithCommas(n){
var rx= /(\d+)(\d{3})/;
return String(n).replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
<form>
Price: <input type='text' id='frm_price' onkeyup="charPreview()">    <span id="frm_price_preview">This is where to show number as user is typing</span>
</form>
An answer without loops.
function charPreview(){
var x = document.getElementById("frm_price").value;
document.getElementById("frm_price_preview").innerHTML = numberWithCommas(x);
}
function numberWithCommas(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
<form>
Price: <input type='text' id='frm_price' onkeyup="charPreview()">    <span id="frm_price_preview">This is where to show number as user is typing</span>
</form>
See also accounting.js which handles this sort of thing quite nicely.
Related
Hi I'm new in the community.
I am trying to create a simple page where in there are 3 textbox. 1st text box is where the number will be entered. For 2nd and 3rd textbox is where the result will be shows on a different format as soon as the numbers are entered from the 1st textbox. 2nd text box should show the number with a comma which I was able to do. Example: As soon as I enter a number on the first text box 22 55 01 02 the 2nd text box will show 22,55,01,02 however on the 3rd textbox it should show the same number from 2nd textbox but on Ascending order which I weren't able to do so. Tried searching for a solution already but to now avail. Maybe I am just missing something. Any help will be very much appreciated.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// code for textbox 3 that didn't work
//function sortAscending(a, b)
//{return a - b;
// }
//var points = boxx3.value;
//points.sort(sortAscending);
//document.getElementById("boxx3").innerHTML = points;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<B><br><center>PASTE HERE</br>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>11x5 GAMES</BR>
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games</br>
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="points.sort(sortAscending)">
</body>
It's actually incredibly simple to sort numbers in JavaScript. All you need to do is:
Split the initial string into an array with .split(" ") (splitting on a space).
Sort the numbers with .sort().
Join the numbers back to a string with .join().
Keep in mind that as the output box is an <input>, you'll need to use .value instead of .innerHTML:
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// Fixed code for sorting the numbers
var points = boxx1.value.split(" ");
document.getElementById("boxx3").value = points.sort().join();
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<br>
<center>
<b>PASTE HERE</b>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()" onKeyUp="boxx1KeyPress()">
<br>
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>
11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>
Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend">
</center>
</body>
Also note that you had some slightly invalid HTML in your above snippet (primarily that <br> is a void element, so the tag self-closes and thus </br> is not valid). I've cleaned up the HTML in my snippet above.
Hope this helps! :)
Your main issue is that you are trying to sort something that is still a string... you have to make your string into an array first.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// get an array from our string s
var arr = s.split(',');
arr.sort(); // note that for strings or ints, the default sort is ascending
document.getElementById("boxx3").innerHTML = arr.join(',');
}
I used the String.split method to get an array, separated at the commas, and the Array.join method to turn it back into a string after it was sorted.
Convert comma separated string into Array. Use array sort function and you done.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
}
function sortDisending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return b-a});
document.getElementById("boxx3").value = numberArray;
}
function sortAsending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return a-b});
document.getElementById("boxx3").value = numberArray;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<B><br><center>PASTE HERE
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<br>
<br>11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="sortAsending()">
<input type="button" Value="Descend" onClick="sortDisending()">
<input type="button" Value="Clear Field" onClick="ClearField()">
I am trying to create a tip calculator using HTML and Javascript and each time the user changes the input field for the meal cost and tip amount, I have to validate whether or not it is a number and if it is, I have to cut down the number to 2 decimal places.
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = mealCost.toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = tipPercent.toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge);
var tipPercentage = document.getElementById(tipPercent);
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
I don't think it is taking the values that are edited using toFixed() and also the field tipAmount is showing NaN. How can I fix these errors?
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = parseInt(mealCost).toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = parseInt(tipPercent).toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge).value;
var tipPercentage = document.getElementById(tipPercent).value;
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
The validateMealCost and validateTipPercent functions lacked a parseInt to turn the values to numbers, and the calculateTipAmount function lacked a .value, turning it to NaN.
you need to parse the inputs - all the text inputs will provide strings and therefore cannot be compared to others numbers as a number not can they be in that form nor can they be used for calculations. Also note that even if you have used a number to do calculations, using .toFixed() will convert that number to a string.
For example - you will need to use parseInt or parseFloat which will return a number:
var tipPercent = parseInt(document.getElementById(tipPercent).value);
It is not updating because you need to declare the input before the script. So the simple fix for this would be to move the entire <script> tag to below the last occurrence of <input>.
You can emulate the result using the W3Schools Tryit Editor and pasting a snippet of your code:
<!DOCTYPE html>
<html>
<body>
The content of the body element is displayed in your browser.
<input type="text" id="tipAmount" />
<script>
document.getElementById('tipAmount').value = 5*5;
document.getElementById('tipAmount2').value = 5*5;
</script>
<input type="text" id="tipAmount2" />
</body>
</html>
Notice how the code only updates tipAmount and not tipAmount2.
I want to create a HTML page that can do the following tasks:
Take a number from the user
Calculate a multiplication table and show it below the calculate button
Format of multiplication table should be like this, but on the same page and below the calculate button:
5
10
15
20
25
30
35
40
45
50
But I am getting NaN error, and also need help with how to get table displayed like this on the same page, please help and bear with my newbie mistakes :-)
<!doctype html>
<html>
<head>
<title>Multiplication Table</title>
<script type="text/javascript">
function createTable(nn)
{
for(i=1; i<=10; i++)
{
document.getElementById("t1").innerHTML = nn*i;
}
return true;
}
</script>
</head>
<body>
<h1><center>Assignment No.4</center></h1>
<h4><center>Please Enter Number for Table and press the button</center><h4>
<form>
<center><input type="text" name="num" size=10></center><br />
<center><button type="button" onclick="createTable('n')">Calculate</button></center>
</form>
<center><p id="t1"></p></center>
<script type="text/javascript">
m = "num".value;
n = Number(m);
</script>
</body>
</html>
There's no mystery
m = "num".value;
here, m = undefined, because the string "num" has no property called value, i.e. it's undefined
n = Number(m);
Number(undefined) === NaN - because undefined is not a number
edit: also your onclick is called like this - createTable('n')
same problem, 'n' is not a number, it's a string .. 'n' * anything == NaN
There some problem with your program just see this one
<!doctype html>
<html>
<head>
<title>Multiplication Table</title>
<script type="text/javascript">
function createTable()
{
var nn = document.getElementById("num").value;
var str="<table>";
for(i=1; i<=10; i++)
{
str+="<tr><td>" + nn + "*" + i +" = " + (nn*i) + "</td></tr>";
}
str+="</table>";
document.getElementById("t1").innerHTML = str;
}
</script>
</head>
<body>
<h1><center>Assignment No.4</center></h1>
<h4><center>Please Enter Number for Table and press the button</center><h4>
<form>
<center><input type="text" id="num" name="num" size=10></center><br />
<center><button type="button" onclick="createTable()">Calculate</button></center>
</form>
<center><p id="t1"></p></center>
</body>
</html>
You are converting a value to a number, but it's at the wrong time, and it's the wrong value. Then you don't even use the result.
This code:
m = "num".value;
n = Number(m);
is executed when the page loads, so that's before the user has had any chance to enter any number. It doesn't use the field where the user could enter a number, it only uses the string "num". As the string isn't the input element, it doesn't have a property named value, so m gets the value undefined. Turning that into a number gives you NaN, but that's not even the NaN that you get in the output, because the value of n is never used.
This code:
onclick="createTable('n')"
doesn't use the variable n, it uses the string 'n'. That is what gives you the NaN in the output, because that is what you get when you try to use the string in the multiplication. I.e. 'n' * i results in NaN.
To get the value that the user entered, you should get it at the time that the user clicks the button. Put the code in a function so that you can call it at that time. Use the getElementsByName method to locate the element:
function getValue() {
var m = document.getElementsByName("num")[0].value;
return Number(m);
}
When the user clicks the button, call the function to get the value and send it to the function that creates the table:
onclick="createTable(getValue())"
In your code where you create the table, you should put the items together and then put them in the page. If you put each item in the element, they will replace each other and you end up with only the last one. Also, you would want to put an element around each item, otherwise you end up with just a string of digits:
function createTable(nn) {
var str = '';
for(var i = 1; i <= 10; i++) {
str += '<div>' + (nn * i) + '</div>';
}
document.getElementById("t1").innerHTML = str;
}
Demo:
function createTable(nn) {
var str = '';
for(var i = 1; i <= 10; i++) {
str += '<div>' + (nn * i) + '</div>';
}
document.getElementById("t1").innerHTML = str;
}
function getValue() {
var m = document.getElementsByName("num")[0].value;
return Number(m);
}
<h1><center>Assignment No.4</center></h1>
<h4><center>Please Enter Number for Table and press the button</center><h4>
<form>
<center><input type="text" name="num" size=10></center><br />
<center><button type="button" onclick="createTable(getValue())">Calculate</button></center>
</form>
<center><p id="t1"></p></center>
So all this time I thought I was doing it wrong. But can jQuery read decimals? My first textbox has to multiply the input with .10, the second is .05. But I only get 1 as final result. How can I fix it?
<!DOCTYPE html>
<head>
<title>Test</title>
<script src="../js/jquery-1.11.1.min.js"></script>
<head>
<body>
<input id="first" type="text" />
<script>
$('#first').on('change', function () {
$(this).val($(this).val() * .10);
compute();
});
</script>
<input id="second" type="text" />
<script>
$('#second').on('change', function () {
$(this).val($(this).val() * .05);
compute();
});
</script>
<script>
function compute() {
var first = ~~$('#first').val();
var second = ~~$('#second').val();
var result = $('#result');
var grade = first + second;
result.val(grade);
}
</script>
<input id="result" type="text" readonly />
</body>
</html>
I believe you want to change compute() to this:
function compute() {
var first = parseFloat($('#first').val());
var second = parseFloat($('#second').val());
var result = $('#result');
var grade = first + second;
result.val(grade);
}
For example i have a textbox, I am entering 12000 and i want it to look like 12,000 in the textbox How would I do this? Im using html to do the textbox
Try something like this
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;
}
Then use it on your textboxes like so
<input type="text" id="txtBox" onchange="return addCommas(this.value)" />
Hope that helps
Use the jQuery autoNumeric plugin:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Input with separator</title>
<script type="text/javascript" src="jquery-1.11.0.js"></script>
<script type="text/javascript" src="autoNumeric.js"></script>
<script type="text/javascript">
$( document ).ready( function() {
$("#myinput").autoNumeric(
'init', {aSep: ',', mDec: '0', vMax: '99999999999999999999999999'}
);
});
</script>
</head>
<body>
<input id="myinput" name="myinput" type="text" />
</body>
</html>
This is probably a bad idea...
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Comma Thousands Input</title>
<style>
label, input, button{font-size:1.25em}
</style>
<script>
// insert commas as thousands separators
function addCommas(n){
var rx= /(\d+)(\d{3})/;
return String(n).replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
// return integers and decimal numbers from input
// optionally truncates decimals- does not 'round' input
function validDigits(n, dec){
n= n.replace(/[^\d\.]+/g, '');
var ax1= n.indexOf('.'), ax2= -1;
if(ax1!= -1){
++ax1;
ax2= n.indexOf('.', ax1);
if(ax2> ax1) n= n.substring(0, ax2);
if(typeof dec=== 'number') n= n.substring(0, ax1+dec);
}
return n;
}
window.onload= function(){
var n1= document.getElementById('number1'),
n2= document.getElementById('number2');
n1.value=n2.value='';
n1.onkeyup= n1.onchange=n2.onkeyup=n2.onchange= function(e){
e=e|| window.event;
var who=e.target || e.srcElement,temp;
if(who.id==='number2') temp= validDigits(who.value,2);
else temp= validDigits(who.value);
who.value= addCommas(temp);
}
n1.onblur= n2.onblur= function(){
var temp=parseFloat(validDigits(n1.value)),
temp2=parseFloat(validDigits(n2.value));
if(temp)n1.value=addCommas(temp);
if(temp2)n2.value=addCommas(temp2.toFixed(2));
}
}
</script>
</head>
<body>
<h1>Input Thousands Commas</h1>
<div>
<p>
<label> Any number <input id="number1" value=""></label>
<label>2 decimal places <input id="number2" value=""></label>
</p></div>
</body>
</html>
You can use the Javascript Mask API
You can try this simple Javascript
<script type="text/javascript">
function addcommas(x) {
//remove commas
retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;
//apply formatting
return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
HTML Code
<div class="form-group">
<label>Amount </label>
<input type="text" name="amount" onkeyup="this.value=addcommas(this.value);"class="form-control" required="">
</div>
For user input I would recommend not formatting the value to include a comma. It will be much easier to deal with an integer value (12000), than a string value (12,000) once submitted.
However if you are certain on formatting the value, then as #achusonline has recommended, I would mask the value. Here is a jQuery plugin which would be useful to get this result:
http://digitalbush.com/projects/masked-input-plugin/
adding punctuation or commas of numbers on input change.
html code
<input type="text" onkeyup="this.value=addPunctuationToNumbers(this.value)">
Javascript Code
<script>
function addPunctuationToNumbers(number) {
return number.replace(/(\d{3})(?=\d)/g, "$1,");
}
</script>
<!DOCTYPE html>
<html>
<body>
<h1>On change add pumctuation to numbers</h1>
<input type="text" onkeyup="this.value=addPunctuationToNumbers(this.value)">
<script>
function addPunctuationToNumbers(number) {
return number.replace(/(\d{3})(?=\d)/g, "$1,");
}
</script>
</body>
</html>
You can use very handy JavaScript method, called Intl.NumberFormat:
<script>
//Value formatting
document.getElementById('your-input-id').addEventListener('change', function(event) {
//Check for specific CSS class of your input first
if (event.target.classList.contains('some-css-class')) {
// remove any commas from earlier formatting
const value = event.target.value.replace(/,/g, '');
// try to convert to an integer
const parsed = parseInt(value);
//NumberFormat options
const options = {
style: 'decimal',
maximumFractionDigits: 10,
useGrouping: true,
maximumSignificantDigits: 20,
};
// check if the integer conversion worked and matches the expected value
if (!isNaN(parsed) && parsed == value) {
// update the value
event.target.value = new Intl.NumberFormat('en-GB', options).format(value);
}
}
});
</script>