Decimal point on number input - javascript

Is it possible to add a decimal on a number input, as a user types?
I have the below input:
<div class="form-control">
<label for="bill">Bill</label>
<input
type="number"
id="bill"
name="bill"
placeholder="0"
maxlength="6"
/>
And I want it to look like the below as I type:
I've tried to set the input.value and wrap it in formatter.format(), using the below, but I get a parsing error. Because of the $ sign and it being a number input, I'm guessing.
let formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD', });
Is there anyway to do this?

Use regex to remove non digits, then add the decimal using string function.
document.getElementById('bill').addEventListener('input', function(){
if(this.value.length > 2){
var val = this.value.replace(/[^\d]/, '');
val = val.substr(0, val.length-2)+"."+val.substr(-2);
this.value = val;
}
});
<input
type="number"
id="bill"
name="bill"
placeholder="0"
maxlength="6"
/>

Related

Format value in text input to currency

I have made a small calculator, where I want the sum in to be displayed with the format currency in the readonly input text.
Since I'm new to javascript (and this forum), I can't get it to work.
Thought my code below would work. Can anyone give me some pointers on how to make it work?
<h2>Calculator/h2>
<input
type="text"
id="number1"
value="0"
onchange="summa.value = (number1.value*1) + (number2.value*1)"
/>
<br>
<input
type="text"
id="number2"
value="0"
onchange="summa.value = (number1.value*1) + (number2.value*1)"
/>
<br/><br/>
<input
type="text"
readonly="readonly"
id="summa"
value="0"
onchange="this.value.toLocaleString("sv-SE", {
style:"currency",
currency:"SEK",
currencyDisplay:"symbol",
maximumFractionDigits: 0
});"
/>
Your code as posted shows quite a few typos, but the main reason it 'doesn't work' is that programatic changes to an input don't trigger a change event. It will be far clearer to abstract your methods into its own script and then appropriately handle the changes and update the total.
Here is a minimal example of your logic abstracted into html and a separate script. The inputs have been changed to type="number" to avoid entering non-numeric values. The script then queries the three inputs using getElementById and attaches change listeners to the two accepting input using addEventListener. Finally there is a single function declared to update the value of the third input with the formatted value.
const number1 = document.getElementById('number1');
const number2 = document.getElementById('number2');
const summa = document.getElementById('summa');
function updateTotal() {
const total = Number(number1.value) + Number(number2.value);
summa.value = total.toLocaleString('sv-SE', {
style: 'currency',
currency: 'SEK',
currencyDisplay: 'symbol',
maximumFractionDigits: 0,
});
}
number1.addEventListener('change', updateTotal);
number2.addEventListener('change', updateTotal);
<h2>Calculator</h2>
<input type="number" id="number1" value="0"/>
<br />
<input type="number" id="number2" value="0" />
<br />
<input type="text" id="summa" readonly="true" value="0"/>
note: your method of coercing a string to number is valid, but there are more transparent methods. Here I'm using the Number constructor directly but there are plenty of other methods
If you somehow feel that you need to do this all inline you can apply the same logic, but you'll instantly note the amount of duplicated code.
<h2>Calculator</h2>
<input type="number" id="number1" value="0" onchange="summa.value = (Number(number1.value) + Number(number2.value)).toLocaleString('sv-SE', {
style: 'currency',
currency: 'SEK',
currencyDisplay: 'symbol',
maximumFractionDigits: 0,
});" />
<br />
<input type="number" id="number2" value="0" onchange="summa.value = (Number(number1.value) + Number(number2.value)).toLocaleString('sv-SE', {
style: 'currency',
currency: 'SEK',
currencyDisplay: 'symbol',
maximumFractionDigits: 0,
});" />
<br />
<input type="text" readonly="readonly" id="summa" value="0" />
Alternatively you can include an inline script as a decent compromise.
<h2>Calculator</h2>
<input type="number" id="number1" value="0" />
<br />
<input type="number" id="number2" value="0" />
<br />
<input type="text" id="summa" readonly="true" value="0" />
<script type="module">
const number1 = document.getElementById('number1');
const number2 = document.getElementById('number2');
const summa = document.getElementById('summa');
function updateTotal() {
const total = Number(number1.value) + Number(number2.value);
summa.value = total.toLocaleString('sv-SE', {
style: 'currency',
currency: 'SEK',
currencyDisplay: 'symbol',
maximumFractionDigits: 0,
});
}
number1.addEventListener('change', updateTotal);
number2.addEventListener('change', updateTotal);
</script>

how to calculate a number in 2 decimals behind the dot

This is my form:
<input type="text" class="form-control amount" value="" placeholder="amount" />
<input type="hidden" class="price" value="3.30" />
<input type="text" class="form-control total" value="" disabled />
My js:
$('.amount').on('keyup', function (e) {
e.preventDefault();
var amount = $('.amount').val();
var total = Number(amount) * Number($('.price').val());
$('.total').val(total);
});
If i fill in an amount of 3, the result in input with class total shows me: 9.899999999999999 instead of 19.80. (3 * 3.30 is exactly 9.90).
Can someone explain me why the result is so many chars behind the dot?
I know i can reduce the result in 2 decimals with .toFixed(2) but that doesn't explain for me why a value which is exactly 9.90 changes into 9.899999999999999
Fiddle
This is because the way float numbers are stored as binary digits. To enable a wide rage of numbers and still maintain a reasonable size in memory for each number, the precision of results is sacrificed a bit. You can read more about here https://stackoverflow.com/a/588014/3807365
This happens due to the how floating point arithmetic works. In a few words, the floating number is not represented internally as-is, so when the language goes back and forth to display it, there can be some precision issues (such as the one you are facing). See the link for more details.
In summary, as you seem to be handling currency calculations, your best option is to use, instead of float, a specific datatype such as currency.js:
$('.amount').on('keyup', function (e) {
e.preventDefault();
var amount = $('.amount').val();
var total = currency(amount).multiply(currency($('.price').val()));
$('.total').val(total);
});
<script src="https://cdn.jsdelivr.net/npm/currency.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control amount" value="" placeholder="amount" />
<input type="hidden" class="price" value="3.30" />
<input type="text" class="form-control total" value="" disabled />
There are many libs for that, another one is dinero.js.

Javascript check if an input is a Long or not [duplicate]

How do I limit or restrict the user to only enter a maximum of five characters in the textbox?
Below is the input field as part of my form:
<input type="text" id="sessionNo" name="sessionNum" />
Is it using something like maxSize or something like that?
maxlength:
The maximum number of characters that will be accepted as input. This can be greater that specified by SIZE , in which case the field
will scroll appropriately. The default is unlimited.
<input type="text" maxlength="2" id="sessionNo" name="sessionNum" onkeypress="return isNumberKey(event)" />
However, this may or may not be affected by your handler. You may need to use or add another handler function to test for length, as well.
The simplest way to do so:
maxlength="5"
So.. Adding this attribute to your control:
<input type="text"
id="sessionNo"
name="sessionNum"
onkeypress="return isNumberKey(event)"
maxlength="5" />
Add the following to the header:
<script language="javascript" type="text/javascript">
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
}
}
</script>
<input type="text" id="sessionNo" name="sessionNum" onKeyDown="limitText(this,5);"
onKeyUp="limitText(this,5);"" />
Make it simpler
<input type="text" maxlength="3" />
and use an alert to show that max chars have been used.
According to w3c, the default value for the MAXLENGTH attribute is an unlimited number. So if you don't specify the max a user could cut and paste the bible a couple of times and stick it in your form.
Even if you do specify the MAXLENGTH to a reasonable number make sure you double check the length of the submitted data on the server before processing (using something like php or asp) as it's quite easy to get around the basic MAXLENGTH restriction anyway
<input type="text" maxlength="5">
the maximum amount of letters that can be in the input is 5.
Maxlength
The maximum number of characters that will be accepted as input.
The maxlength attribute specifies the maximum number of characters allowed in the element.
Maxlength W3 schools
<form action="/action_page.php">
Username: <input type="text" name="usrname" maxlength="5"><br>
<input type="submit" value="Submit">
</form>
I always do it like this:
$(document).ready(function() {
var maxChars = $("#sessionNum");
var max_length = maxChars.attr('maxlength');
if (max_length > 0) {
maxChars.on('keyup', function(e) {
length = new Number(maxChars.val().length);
counter = max_length - length;
$("#sessionNum_counter").text(counter);
});
}
});
Input:
<input name="sessionNum" id="sessionNum" maxlength="5" type="text">
Number of chars: <span id="sessionNum_counter">5</span>
You can use
<input type = "text" maxlength="9">
or
<input type = "number" maxlength="9"> for numbers
or
<input type = "email" maxlength="9"> for email
validation will show up
<input type="number" id="xxx" name="xxx" oninput="maxLengthCheck(this)" maxlength="10">
function maxLengthCheck(object) {
if (object.value.length > object.maxLength)
object.value = object.value.slice(0, object.maxLength)
}
The following code includes a counted...
var count = 1;
do {
function count_down(obj, count){
let element = document.getElementById('count'+ count);
element.innerHTML = 80 - obj.value.length;
if(80 - obj.value.length < 5){
element.style.color = "firebrick";
}else{
element.style.color = "#333";
}
}
count++;
} while (count < 20);
.text-input {
padding: 8px 16px;
width: 50%;
margin-bottom: 5px;
margin-top: 10px;
font-size: 20px;
font-weight: 700;
font-family: Raleway;
border: 1px solid dodgerblue;
}
<p><input placeholder="Title" id="bike-input-title" onkeyup="count_down(this, 3)" maxlength="80" class="text-input" name="bikeTitle" ></p>
<span id="count3" style="float: right; font-family: Raleway; font-size:20px; font-weight:600; margin-top:-5px;">80</span><br>
Late to the party, but if you want a full proof way to restrict numbers or letters that is simply javascript and also limits length of characters:
Change the second number after .slice to set the how many characters. This has worked much better for me then maxlength.
Just Numbers:
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').slice(0, 11);
Just Letters:
oninput="this.value=this.value.replace(/[^A-Za-z\s]/g,'').slice(0,20);"
Full example:
<input type="text" name="MobileNumber" id="MobileNumber" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').slice(0, 11);"/>
Use maxlenght="number of charcters"
<input type="text" id="sessionNo" name="sessionNum" maxlenght="7" />
<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);" placeholder="MobileNumber">
<script>
function checkNumber(key) {
console.log(key);
var inputNumber = document.querySelector("#MobileNumber").value;
if(key.key >= 0 && key.key <= 9) {
inputNumber += key.key;
}
else {
key.preventDefault();
}
}
</script>

dijit ValidationTextBox how to add minlength and maxlength

I would like to know how (with simple working example) to add maxlength and minlength to input tag generated by
dijit/form/ValidationTextBox
Example of desired output:
<input maxlength="10" minlength="2" class="dijitReset dijitInputInner" data-dojo-attach-point="textbox,focusNode" autocomplete="off" name="title" type="text" tabindex="0" id="Image-1-title-LabelValidationTextBox" aria-required="undefined" value="Title text for image Image-1" aria-invalid="false">
try this example with regex constraint
<input type="text" value="someTestString" required="true"
data-dojo-type="dijit/form/ValidationTextBox"
data-dojo-props="regExp: '[a-zA-Z0-9$%!_]{2,10}', invalidMessage: 'The value must be at least 2 character and maximum 10'" />
ValidationTextBox has the properties minLength and maxLength. They are used in the following why in a declarative manner.
<input data-dojo-type="dijit/form/ValidationTextBox"
data-dojo-props="required:true,
maxLength:5,
minLength:2"
type="text"
name="exmaple" />
Here's another solution:
registry.byId("validationTextBox").validator = function(value, constraints) {
if(value) {
return value.length >= 2 && value.length <= 10;
}
return true;
}

maxlength=5 not working if input type=number

This is frustrating!
When the input type is text and I gave maxlength as 5, it is not allowing me to enter more than 5 characters
<input type="text" maxlength="5" />
If I gave input type as number and I gave maxlength as 5, it is allowing more than 5 digits?
<input type="number" maxlength="5" pattern="[0-9]*" />
Am I missing something?
PS: This is for mobile responsive site!
Instead of maxlength use max
<input type="number" min="1" max="10000" />
Update
Small jQuery plugin
(function ($) {
$.fn.maxlength = function (length) {
return this.on('keydown', function () {
var maxlength = length || parseInt($(this).attr('maxlength'), 10) ;
if (maxlength && $(this).val().length >= maxlength) {
$(this).val($(this).val().slice(0, maxlength - 1));
}
});
};
}($));
Example
try using max...
<input type="number" max="99999" />
EDIT: Showing Validation
<form id='FormValidation'>
<input id="myNum" type="number" min="1" max="99999" />
<input type="text" maxlength="5" />
<input type="submit" />
</form>
Try adding a number greater than 99999 and hitting submit, check the updated fiddle.
This jquery could help too...
$('#myNum').keyup( function(e){
var max = $('#myNum').attr('max').length;
if ($(this).val().length >= max) {
$(this).val($(this).val().substr(0, max));
}
});
replace maxlength with max
// Max Length = 5
<input type="number" max="99999" />
// length between 1 to 5
<input type="number" min="1" max="99999" />
Updated Answer. It's so simple!
<input type="number" id="nbr"/>
<input type="text" maxlength="5" />
$(document).on('keypress','#nbr', function(e){
if($(this).val().length >= 5)
{
e.preventDefault();
}
});
And you can add a max attribute that will specify the highest possible number that you may insert
<input type="number" max="999" />
if you add both a max and a min value you can specify the range of allowed values:
<input type="number" min="1" max="999" />

Categories

Resources