Set value to currency in input type=number /
In the end I made a jQuery plugin that will format the <input type="number" />
appropriately for me. I also noticed on some mobile devices the min
and max
attributes don't actually prevent you from entering lower or higher numbers than specified, so the plugin will account for that too. Below is the code and an example:
(function($) { $.fn.currencyInput = function() { this.each(function() { var wrapper = $("<div class='currency-input' />"); $(this).wrap(wrapper); $(this).before("<span class='currency-symbol'>$</span>"); $(this).change(function() { var min = parseFloat($(this).attr("min")); var max = parseFloat($(this).attr("max")); var value = this.valueAsNumber; if(value < min) value = min; else if(value > max) value = max; $(this).val(value.toFixed(2)); }); }); };})(jQuery);
$(document).ready(function() { $('input.currency').currencyInput();});
.currency { padding-left:12px;}
.currency-symbol { position:absolute; padding: 2px 5px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><input type="number" class="currency" min="0.01" max="2500.00" value="25.00" />
Format currency input field with dollar sign & commas
Well here's a way, though in truth not as simple as I hoped when I started down this path. You can use Intl.NumberFormat to get the comma in there (according to locale). To accomodate decimals, I sniff for them in the beginning and append them to the result.
To allow for the comma, I made this a text field with a pattern attribute. Also, I adjusted your CSS to make it a little nicer looking with the $
$('#price').keydown(function(e) {
setTimeout(() => {
let parts = $(this).val().split(".");
let v = parts[0].replace(/\D/g, ""),
dec = parts[1]
let calc_num = Number((dec !== undefined ? v + "." + dec : v));
// use this for numeric calculations
// console.log('number for calculations: ', calc_num);
let n = new Intl.NumberFormat('en-EN').format(v);
n = dec !== undefined ? n + "." + dec : n;
$(this).val(n);
})
})
.body {
text-align: left;
}
.fields {
margin: 0 10px 0 0;
}
.fields:before {
content: "$";
text-align: center;
position: relative;
left: 35px;
}
#price {
border-radius: 5px;
margin: 15px;
padding: 10px 10px 10px 20px;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="rev-calculator">
<label for="price">Monthly Revenue</label>
<div class="fields">
<input type="text" pattern="[0-9.,]+" name="price" id="price" required data-type="number" />
<br>
</form>
HTML text input field with currency symbol
Consider simulating an input field with a fixed prefix or suffix using a span with a border around a borderless input field. Here's a basic kickoff example:
.currencyinput { border: 1px inset #ccc;}.currencyinput input { border: 0;}
<span class="currencyinput">$<input type="text" name="currency"></span>
HTML 5 Currency format
Here's a workaround with an additional input type="text"
:
http://jsfiddle.net/UEVv6/2/
HTML
<input type="text" id="userinput" pattern="[0-9]*">
<br>
<input type="number" id="number">
JS
document.getElementById("userinput").onblur =function (){
//number-format the user input
this.value = parseFloat(this.value.replace(/,/g, ""))
.toFixed(2)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//set the numeric value to a number input
document.getElementById("number").value = this.value.replace(/,/g, "")
}
regex is from here How to print a number with commas as thousands separators in JavaScript
HTML5 number input field with currency symbol in the end of it
You need to give the <span>
some sort of useful display
property so that it will wrap the <input>
. By default this element has a value of inline
. In the example below I've used inline-block
, but block
would do just fine.
See updated fiddle.
.input-symbol-euro { position: relative; display: inline-block; width: 50%;}
.input-symbol-euro input { padding-right: 15px; width: 100%;}
.input-symbol-euro:after { position: absolute; top: 50%; transform: translateY(-50%); margin: auto; content: "€"; right: 20px;}
.form-control { display: block; height: 34px; padding: 6px 12px; font-size: 14px; line-height: 1.42857143; color: #555; background-color: #fff; background-image: none; border: 1px solid #ccc; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s; -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;}
.form-control:focus { border-color: #66afe9; outline: 0; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, .6); box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, .6);}
.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control { cursor: not-allowed; background-color: #eee; opacity: 1;}
<span class="input-symbol-euro"> <input type="number" value="0" min="0" step="1" class="form-control" /></span>
HTML5 Form Input Pattern Currency Format
If you want to allow a comma delimiter which will pass the following test cases:
0,00 => true
0.00 => true
01,00 => true
01.00 => true
0.000 => false
0-01 => false
then use this:
^\d+(\.|\,)\d{2}$
Convert input value to currency format when user type
There are a couple of problems with your code:
- You're using comma when binding multiple event handlers to the input box.
- You're not converting the received value to a number before applying
toLocaleString
on it. - You're not setting the value of the textbox again after conversion.
Correcting these, here is a working demo. For the sake of simplicity, I've removed the other event handlers, except blur
, as keyup
was causing problems.
$('input.CurrencyInput').on('blur', function() { const value = this.value.replace(/,/g, ''); this.value = parseFloat(value).toLocaleString('en-US', { style: 'decimal', maximumFractionDigits: 2, minimumFractionDigits: 2 });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><input class="CurrencyInput">
Dealing with currency in Javascript
Why not a regex ?
<input type=“text” pattern=“^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$” />
PS: i just copy pasted the first regex I found if that one does not fill yow needs go to google a look for regex currency
Related Topics
How to Forcefully Print Background Image in HTML
Does CSS Grid Have a Flex-Grow Function
Why People Minify Assets and Not The HTML
Text-Align: Right on <Select> or <Option>
Open PDF File in New Window from Variable Path Name in Gsp Page
HTML 5 Input Type='Date' Disable Keyboard Input
With HTML5 Url Input Validation Assume Url Starts with Http://
How to Alternate HTML Table Row Colors Using Jsp
Using Cm/Mm on The CSS of a Web App That Replicates Paper Interaction Is a Good Practice
How to Break Word After Special Character Like Hyphens (-)
Why Isn't My Textarea's Placeholder Showing Up
How to Add an Offsetted Outline to a CSS Shape
CSS Override Rules and Specificity
Flipping/Inverting/Mirroring Text Using CSS Only
Wget Recognizes Some Part of My Url Address as a Syntax Error
How to Restrict My Input Type="File" to Accept Only Png Image Files Not Working in Firefox