JS - onkeyup (dynamic calculation) - onkeyup

A very simple table, one cell takes a number and the second one (read-only)
displays on-the-fly the double of that number. But, something does not work. Nothing happens:
html:
<td><input type="text" id="qantity" name="qantity" onkeyup="getValues()"
class="number" value="" autofocus placeholder="0"
onfocus="this.placeholder = ''"
onblur="this.placeholder = '0'"
onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
</input></td>
<td id="total" name="total" class="right">0.00</td>
js:
<script>
function getValues(){
var var_qantity = Number(document.getElementById("qantity").value);
var var_total = var_qantity * 2;
document.getElementById("total").value = var_total;
}
</script>

Replace
document.getElementById("priceOriginal").value = var_total;
with
document.getElementById("total").innerHTML = var_total;
Now the doubled value will be visible as soon as the number is typed in the textbox.
If you need additional functionality, please be a bit specific.
Hope this helps.

Related

How to specify max length of 6 numbers only in input type number field [duplicate]

The maxlength attribute is not working with <input type="number">. This happens only in Chrome.
<input type="number" class="test_css" maxlength="4" id="flight_number" name="number"/>
From MDN's documentation for <input>
If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the maximum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored.
So maxlength is ignored on <input type="number"> by design.
Depending on your needs, you can use the min and max attributes as inon suggested in his/her answer (NB: this will only define a constrained range, not the actual character length of the value, though -9999 to 9999 will cover all 0-4 digit numbers), or you can use a regular text input and enforce validation on the field with the new pattern attribute:
<input type="text" pattern="\d*" maxlength="4">
Max length will not work with <input type="number" the best way i know is to use oninput event to limit the maxlength. Please see the below code.
<input name="somename"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "6"
/>
Many guys posted onKeyDown() event which is not working at all i.e. you can not delete once you reach the limit. So instead of onKeyDown() use onKeyPress() and it works perfectly fine.
Below is working code:
User will not be allowed to enter more than 4 digits
<br>
<input type="number" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==4) return false;" />
I have two ways for you do that
First: Use type="tel", it'll work like type="number" in mobile, and accept maxlength:
<input type="tel" />
Second: Use a little bit of JavaScript:
<!-- maxlength="2" -->
<input type="tel" onKeyDown="if(this.value.length==2 && event.keyCode!=8) return false;" />
You can use the min and max attributes.
The following code do the same:
<input type="number" min="-999" max="9999"/>
This works in Android as well
Change your input type to text and use "oninput" event to call function:
<input type="text" oninput="numberOnly(this.id);" maxlength="4" id="flight_number" name="number"/>
Now use Javascript Regex to filter user input and limit it to numbers only:
function numberOnly(id) {
// Get element by id which passed as parameter within HTML element event
var element = document.getElementById(id);
// This removes any other character but numbers as entered by user
element.value = element.value.replace(/[^0-9]/gi, "");
}
Demo: https://codepen.io/aslami/pen/GdPvRY
For React users,
Just replace 10 with your max length requirement
<input type="number" onInput={(e) => e.target.value = e.target.value.slice(0, 10)}/>
how to limit input type max length
<input name="somename"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "6"
/>
You can try this as well for numeric input with length restriction
<input type="tel" maxlength="4" />
I once got into the same problem and found this solution with respect to my needs.
It may help Some one.
<input type="number" placeholder="Enter 4 Digits" max="9999" min="0"
onKeyDown="if(this.value.length==4 && event.keyCode>47 && event.keyCode < 58)return false;"
/>
Happy Coding :)
try use tel :
maxlength="5" type="tel"
I wrote a small and clean workaround. Using this function will make it work, as it should
const inputHandler = (e) => {
const { value, maxLength } = e.target;
if (String(value).length >= maxLength) {
e.preventDefault();
return;
}
};
For example, it can be used in React like this:
<input
type="number"
maxlength="4"
onKeyPress={inputHandler}
/>
this code worked for me
<form method="post">
<label for="myNumber">My Number:</label>
<input type="number" maxlength="9" required
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" >
<br><br>
<input type="submit" value="Submit">
</form>
Chrome (technically, Blink) will not implement maxlength for <input type="number">.
The HTML5 specification says that maxlength is only applicable to the types text, url, e-mail, search, tel, and password.
<input type="number" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" onKeyDown="if(this.value.length==10 && event.keyCode!=8) return false;">
DEMO - JSFIDDLE
Here is my solution with jQuery...
You have to add maxlength to your input type=number
$('body').on('keypress', 'input[type=number][maxlength]', function(event){
var key = event.keyCode || event.charCode;
var charcodestring = String.fromCharCode(event.which);
var txtVal = $(this).val();
var maxlength = $(this).attr('maxlength');
var regex = new RegExp('^[0-9]+$');
// 8 = backspace 46 = Del 13 = Enter 39 = Left 37 = right Tab = 9
if( key == 8 || key == 46 || key == 13 || key == 37 || key == 39 || key == 9 ){
return true;
}
// maxlength allready reached
if(txtVal.length==maxlength){
event.preventDefault();
return false;
}
// pressed key have to be a number
if( !regex.test(charcodestring) ){
event.preventDefault();
return false;
}
return true;
});
And handle copy and paste:
$('body').on('paste', 'input[type=number][maxlength]', function(event) {
//catch copy and paste
var ref = $(this);
var regex = new RegExp('^[0-9]+$');
var maxlength = ref.attr('maxlength');
var clipboardData = event.originalEvent.clipboardData.getData('text');
var txtVal = ref.val();//current value
var filteredString = '';
var combined_input = txtVal + clipboardData;//dont forget old data
for (var i = 0; i < combined_input.length; i++) {
if( filteredString.length < maxlength ){
if( regex.test(combined_input[i]) ){
filteredString += combined_input[i];
}
}
}
setTimeout(function(){
ref.val('').val(filteredString)
},100);
});
I hope it helps somebody.
Input type text and oninput event with regex to accept only numbers worked for me.
<input type="text" maxlength="4" oninput="this.value=this.value.replace(/[^0-9]/g,'');" id="myId"/>
Try this,
<input type="number" onkeypress="return this.value.length < 4;" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />
The below code will allow the user to:
Enter digits only in the 0-999 range.
This also restricts the user not to enter more than 3 characters.
When the user enters more than 3 characters then it will clear the textbox.
<input type="number" name="test_name" min="0" max="999" oninput="validity.valid||(value='');">
If you want to do it in a React Function Component or without using "this", here is a way to do it.
<input onInput={handleOnInput}/>
const handleOnInput = (e) => {
let maxNum = 4;
if (e.target.value.length > maxNum) {
e.target.value = e.target.value.slice(0, maxNum);
}
};
In my experience most issues where people are asking why maxlength is ignored is because the user is allowed to input more than the "allowed" number of characters.
As other comments have stated, type="number" inputs do not have a maxlength attribute and, instead, have a min and max attribute.
To have the field limit the number of characters that can be inserted while allowing the user to be aware of this before the form is submitted (browser should identify value > max otherwise), you will have to (for now, at least) add a listener to the field.
Here is a solution I've used in the past: http://codepen.io/wuori/pen/LNyYBM
maxlength ignored for input type="number"
That's correct, see documentation here
Instead you can use type="text" and use javascript function to allow number only.
Try this:
function onlyNumber(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
return true;
}
<input type="text" maxlength="4" onkeypress="return onlyNumber(event)">
I know there's an answer already, but if you want your input to behave exactly like the maxlength attribute or as close as you can, use the following code:
(function($) {
methods = {
/*
* addMax will take the applied element and add a javascript behavior
* that will set the max length
*/
addMax: function() {
// set variables
var
maxlAttr = $(this).attr("maxlength"),
maxAttR = $(this).attr("max"),
x = 0,
max = "";
// If the element has maxlength apply the code.
if (typeof maxlAttr !== typeof undefined && maxlAttr !== false) {
// create a max equivelant
if (typeof maxlAttr !== typeof undefined && maxlAttr !== false){
while (x < maxlAttr) {
max += "9";
x++;
}
maxAttR = max;
}
// Permissible Keys that can be used while the input has reached maxlength
var keys = [
8, // backspace
9, // tab
13, // enter
46, // delete
37, 39, 38, 40 // arrow keys<^>v
]
// Apply changes to element
$(this)
.attr("max", maxAttR) //add existing max or new max
.keydown(function(event) {
// restrict key press on length reached unless key being used is in keys array or there is highlighted text
if ($(this).val().length == maxlAttr && $.inArray(event.which, keys) == -1 && methods.isTextSelected() == false) return false;
});;
}
},
/*
* isTextSelected returns true if there is a selection on the page.
* This is so that if the user selects text and then presses a number
* it will behave as normal by replacing the selection with the value
* of the key pressed.
*/
isTextSelected: function() {
// set text variable
text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return (text.length > 0);
}
};
$.maxlengthNumber = function(){
// Get all number inputs that have maxlength
methods.addMax.call($("input[type=number]"));
}
})($)
// Apply it:
$.maxlengthNumber();
Done! Numbers only and maxlength work perfect.
<input maxlength="5" data-rule-maxlength="5" style="height:30px;width: 786px;" type="number" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />
This code worked quite nicely for me.
In the input with type="number", you can add the following attribute:
oninput="constrainUserInput(this.id)"
The full input will look like this:
<input type="number" class="test_css" maxlength="4" oninput="constrainUserInput(this.id)" id="flight_number" name="number"/>
Note: You must assign your input and ID for this method to work
Then you can add the following JavaScript to your HTML, which basically replaces any characters that exceed your maxlength attribute with an empty quote (essentially removing them):
function constrainUserInput(id) {
let input = document.getElementById(id);
let value = input.value;
if (value.length > input.maxLength) {
input.value = value.substring(0, input.maxLength);
}
}
The absolute solution that I've recently just tried is:
<input class="class-name" placeholder="1234567" name="elementname" type="text" maxlength="4" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" />
As per the Neha Jain's answer above ,I just added below code to common area
$(':input[type="number"]').on('input', function() {
if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);
});
then you can use maxlength="4" like text type fields.
<input type="number"> is just that... a number input (albeit, unconverted from a string to float via Javascript).
My guess, it doesn't restrict characters on key input by maxLength or else your user could be stuck in a "key trap" if they forgot a decimal at the beginning (Try putting a . at index 1 when an <input type"text"> "maxLength" attr has already been reached). It will however validate on form submit if you set a max attribute.
If you're trying to restrict/validate a phone number, use the type="tel" attr/value. It obeys the maxLength attr and brings up the mobile number keyboard only (in modern browsers) and you can restrict input to a pattern (i.e. pattern="[0-9]{10}").
<input type="number" min="1" onKeyPress="if(this.value.length==5) return false"/>
Use type number with min and handle max with onKeyPress
<input type="number" min="1" onKeyPress="if(this.value.length==5) return false"/>
I will make this quick and easy to understand!
Instead of maxlength for type='number' (maxlength is meant to define the maximum amount of letters for a string in a text type), use min='' and max='' .
Cheers

html numeric input allow 6 digits only

I have a input. I want only numeric values.
And I want there to be six numbers only.
How do i do it?
I have:
<input type="number" placeholder="YYMMDD" id="myKadA" maxlength="6" style="width:90px !important" onchange="checkMyKad()" size="8" class="form-control block-centered ic-input" required>
There is a css to remove the scroll bar from the input boxes.
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
-webkit-appearance: textfield;
}
Previously it was input type="text" and maxlength="6" limited it to six chars long. How do i now specify a number 6 digit only
JAVASCRIPT WAY
HTML
<input type="number" placeholder="YYMMDD" id="myKadA" onkeydown="limit(this, 6);" onkeyup="limit(this, 6);" onkeyup="this.value = minmax(this.value, 0, 6)" required>
JS
function limit(element, max_chars)
{
if(element.value.length > max_chars) {
element.value = element.value.substr(0, max_chars);
}
}
function minmax(value, min, max)
{
if(parseInt(value) < min || isNaN(parseInt(value)))
return 0;
else if(parseInt(value) > max)
return 100;
else return value;
}
HTML WAY
<input type="number" placeholder="YYMMDD" id="myKadA" maxlength="6" min="0" max="6" required>
JQUERY WAY
<input type="number" placeholder="YYMMDD" id="myKadA" min="0" max="6" required>
var max_chars = 6;
$('#myKadA').keydown( function(e){
if ($(this).val().length >= max_chars) {
$(this).val($(this).val().substr(0, max_chars));
}
});
$("#myKadA").change(function() {
var max = parseInt($(this).attr('max'));
var min = parseInt($(this).attr('min'));
if ($(this).val() > max)
{
$(this).val(max);
}
else if ($(this).val() < min)
{
$(this).val(min);
}
});
Use the attribute max and min for input type number
Try
<input type="number" onKeyPress="if(this.value.length==6) return false;"/>
or else you can change the input type to "month"
<input type="month" min="2018-03" value="2018-05">
Hope this works.
this looks like a promising answer to your case.
As you have mention in placeholder -YYMMDD
I would suggest you to use input type="date"
Max length will not work with .
You have to make use of jQuery/Javascript.
Below is a working snippet.
HTML:
<form>
<label for="myKadA" class="control-label">Number:</label>
<input type="number" id="myKadA" data-max="6" class="form-control" required>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
jQuery:
<script>
$(document).ready(function () {
$(".btn-primary").click(function (e) {
e.preventDefault();
var keyObj = $("#myKadA");
var maxLength = parseInt(keyObj.attr('data-max'));
if((keyObj).val().length !== maxLength){
alert("You must enter exactly " + maxLength + " digits");
}
});
})
</script>
Since maxlength attribute is ignored with <input type"number"/> as explained here.
You could try adding some validation with javascript using something like:
HTML
<input onKeyDown="validateNum(event, this)" type="text" maxlength="6" max="6" min="6" placeholder="YYMMDD" id="myKadA" style="width:90px !important" onchange="checkMyKad()" class="form-control block-centered ic-input" required>
Javascript
function validateNum(event, input) {
event.preventDefault();
var currVal = input.value ? input.value : "";
// Checks if the key pressed is a number and the right length
if(!isNaN(event.key) && currVal.length < 6){
input.value = currVal + event.key;
}
// Backspace functionality
else if(event.keyCode == 8 && currVal > 0) {
input.value = input.value.slice(0, -1);
}
}
Try to write maxlength=6 without quotes. I tried it in react js like this way: maxLength={6}; and it helped me.
If you want only numbers in input field,
<input type="number" max="6"/>
so it renders into input type number field which allows only 6 digits

How to avoid Decimal values in input type number

How to avoid Decimal values from input of Number in HTML5. Currently it allows user to type decimal value.
An alternative to the supplied answers is to monitor the keypress while in the input. I personally like leaving the type="number" as an attribute. Here's a JSFiddle
<form action="#" method="post">
Numbers: <input name="num"
type="number"
min="1"
step="1"
onkeypress="return event.charCode >= 48 && event.charCode <= 57"
title="Numbers only">
<input type="submit">
</form>
I ended up checking to see if a user types in a period then preventing the event from propagating.
Edit: A better approach. The key press event has been deprecated. Also added in a regex to strip out everything but numbers [0-9] on paste.
<input type="number" onkeydown="if(event.key==='.'){event.preventDefault();}" oninput="event.target.value = event.target.value.replace(/[^0-9]*/g,'');">
Caution Experimental. Only partially works on chrome:
Wanted to look at a great way to grab the pasted value strip everything out then have it placed in input as normal. With the above method you are relying on the event order to correct the input, then any event listeners will ideally fire after. The onpaste method will fire before the input event fires so you keep the flow of events correct. However when replacing the string with only numbers the decimal point would still sneak in. Looking to update this when I find a better solution.
<input type="number" onkeydown="if(event.key==='.'){event.preventDefault();}" onpaste="let pasteData = event.clipboardData.getData('text'); if(pasteData){pasteData.replace(/[^0-9]*/g,'');} " >
Use pattern attribute
<input type="number" name="num" pattern="[0-9]" title="Numbers only">
For more details http://www.w3schools.com/tags/att_input_pattern.asp
FIDDLE
Just plain example using parseInt()
<input type="number" oninput="this.value=(parseInt(this.value)||0)" placeholder="0-9" autofocus='' value='0' />
Based on other answers here, I tried this:
<input id="storeId" min="0" pattern="[0-9]" onkeypress="return !(event.charCode == 46)" step="1" title="Must be an integer number" type="number" >
I just blocked input of dot, but again this does not block paste.
ASCII DOT . character is 46
<input type="number" onkeydown="return event.keyCode !== 190">
This will Restrict period(.) input.For any Key restriction:
https://css-tricks.com/snippets/javascript/javascript-keycodes/
You guys can try this
This function does not allow user to paste unwanted characters and also disallow user to enter .+-E
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"+",
"e",
"."
];
inputBox.addEventListener("input", function() {
this.value = this.value.replace(/[e\+\-\.]/gi, "");
});
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" >
`
If error occured in your JS. You can add this
`$(document).ready(function() { code });
<input type="number" onkeypress="return event.charCode >= 48 && event.charCode <= 57" name="quantity">
Try this :
<input type="number" value="" min="0" oninput="this.value=(parseInt(this.value)||0)" onkeypress="return !(event.charCode == 45||event.charCode == 46||event.charCode == 43)" class="form-control" step="any" />
event.key and event.charCode are deprecated features and don't work well with mobile virtual keyboards. I've done some research and this seems to be the easiest way to make it work.
Tested in Chrome and Firefox on Windows, in Chrome on Android and in Safari on iOS and seems to be working perfectly.
document.getElementById("myInput").addEventListener('beforeinput', e => {
if (!(Number(e.data) >= 0 && Number(e.data) <= 9)) {
e.preventDefault();
}
});
/* unnecessary */
#myInput {
width: 24ch;
}
<input type="number" inputmode="numeric" placeholder="only a number can go here" id="myInput">
By the way, this is my first post here, so please tell me if I'm doing anything wrong.
You should post what you have tried when asking questions.
To use integers only, change the following attribute.
step="any"
to
step="1"
A simple regex can help sort with this issue .
var re = new regExp('[.]+) ;
if(!re.test(num)){listOfNumbers.push(num)};
not letting the user type in a '.' on the input might not be a viable option when you are dealing with multiple cultures and interpretations of '.'.
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode==46))
return false;
return true;
}
#Html.TextBoxFor(model => model.num, new { #class = "form-control input-sm",#maxlength = 5 ,#oninput = "this.value = this.value.replace(/[^0-9]/g, '');"})
In MVC, above solution works.

Allow 2 decimal places in <input type="number">

I have a <input type="number"> and I want to restrict the input of the users to purely numbers or numbers with decimals up to 2 decimal places.
Basically, I am asking for a price input.
I wanted to avoid doing regex. Is there a way to do it?
<input type="number" required name="price" min="0" value="0" step="any">
Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.
More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute
In case anyone is looking for a regex that allows only numbers with an optional 2 decimal places
^\d*(\.\d{0,2})?$
For an example, I have found solution below to be fairly reliable
HTML:
<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />
JS / JQuery:
$(document).on('keydown', 'input[pattern]', function(e){
var input = $(this);
var oldVal = input.val();
var regex = new RegExp(input.attr('pattern'), 'g');
setTimeout(function(){
var newVal = input.val();
if(!regex.test(newVal)){
input.val(oldVal);
}
}, 1);
});
For currency, I'd suggest:
<div><label>Amount $
<input type="number" placeholder="0.00" required name="price" min="0" value="0" step="0.01" title="Currency" pattern="^\d+(?:\.\d{1,2})?$" onblur="
this.parentNode.parentNode.style.backgroundColor=/^\d+(?:\.\d{1,2})?$/.test(this.value)?'inherit':'red'
"></label></div>
See http://jsfiddle.net/vx3axsk5/1/
The HTML5 properties "step", "min" and "pattern" will be validated when the form is submit, not onblur. You don't need the step if you have a pattern and you don't need a pattern if you have a step. So you could revert back to step="any" with my code since the pattern will validate it anyways.
If you'd like to validate onblur, I believe giving the user a visual cue is also helpful like coloring the background red. If the user's browser doesn't support type="number" it will fallback to type="text". If the user's browser doesn't support the HTML5 pattern validation, my JavaScript snippet doesn't prevent the form from submitting, but it gives a visual cue. So for people with poor HTML5 support, and people trying to hack into the database with JavaScript disabled or forging HTTP Requests, you need to validate on the server again anyways. The point with validation on the front-end is for a better user experience. So as long as most of your users have a good experience, it's fine to rely on HTML5 features provided the code will still works and you can validate on the back-end.
Step 1: Hook your HTML number input box to an onchange event
myHTMLNumberInput.onchange = setTwoNumberDecimal;
or in the HTML code
<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />
Step 2: Write the setTwoDecimalPlace method
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(2);
}
You can alter the number of decimal places by varying the value passed into the toFixed() method. See MDN docs.
toFixed(2); // 2 decimal places
toFixed(4); // 4 decimal places
toFixed(0); // integer
Try this for allowing only 2 decimal in input type
<input type="number" step="0.01" class="form-control" />
Or Use jQuery as suggested by #SamohtVII
$( "#ELEMENTID" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
I found using jQuery was my best solution.
$( "#my_number_field" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
I had the same requirement but after checking all these answers I realized there is no inbuilt support to block users from typing a particular number of decimal points. step="0.01" is useful when validating the input for a decimal number but still it will not block users from typing any decimal. In my case, I wanted a solution which will prevent user from entering invalid decimal. So I created my own custom JavaScript function which will enforce user any decimal rule. There is a slight performance issue but for my scenario it is okay to have a very small delay to make sure that user is not typing invalid decimal places. It might be useful for someone who wanted to prevent user from typing invalid decimal value on the input.
You can use this solution with step="0.01" if you want. You can use the below function on your element oninput event. If performance is critical for you, then think to use this on onchange event rather than oninput. And please specify maximum number of decimal places allowed in the input in data-decimal attribute. it can have values from 0 to any number.
function enforceNumberValidation(ele) {
if ($(ele).data('decimal') != null) {
// found valid rule for decimal
var decimal = parseInt($(ele).data('decimal')) || 0;
var val = $(ele).val();
if (decimal > 0) {
var splitVal = val.split('.');
if (splitVal.length == 2 && splitVal[1].length > decimal) {
// user entered invalid input
$(ele).val(splitVal[0] + '.' + splitVal[1].substr(0, decimal));
}
} else if (decimal == 0) {
// do not allow decimal place
var splitVal = val.split('.');
if (splitVal.length > 1) {
// user entered invalid input
$(ele).val(splitVal[0]); // always trim everything after '.'
}
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" data-decimal="0" oninput="enforceNumberValidation(this)" placeholder="No decimal places" value="" />
<input type="number" data-decimal="2" oninput="enforceNumberValidation(this)" placeholder="2 decimal places" value="" />
<input type="number" data-decimal="5" oninput="enforceNumberValidation(this)" placeholder="5 decimal places" value="" />
I might use RegExp to identify invalid value but I have to revert the change in the input as well. So I decided to not use RegExp.
just adding step=".01", sorted my issue.
<input type="number" class="form-control" name="price" step=".01">
Use this code
<input type="number" step="0.01" name="amount" placeholder="0.00">
By default Step value for HTML5 Input elements is step="1".
I had a strange editing experience with some of these solutions. This seems to work pretty well from a user's perspective (only intervene when necessary):
function handleNumberChanged (e) {
const fixed = parseFloat(e.target.value).toFixed(2).toString()
if (fixed.length < parseFloat(e.target.value).toString().length)
e.target.value = fixed
}
This question has been already answer but you can allow decimals
with the step attribute.
you can read more about it here: Allow-decimal-values
This is the solution I've came up with which also stops the user from typing in more that 2 decimals, which a lot of the solutions mentioned above, don't protect against
html:
<input autocomplete="off" type="number" id="priceField" step=".01" min="0" onkeypress="return priceCheck(this, event);"
Javascript:
function priceCheck(element, event) {
result = (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46;
if (result) {
let t = element.value;
if (t === '' && event.charCode === 46) {
return false;
}
let dotIndex = t.indexOf(".");
let valueLength = t.length;
if (dotIndex > 0) {
if (dotIndex + 2 < valueLength) {
return false;
} else {
return true;
}
} else if (dotIndex === 0) {
return false;
} else {
return true;
}
} else {
return false;
}
}
Only 3 decimal point input value in textbox using Javascript.
<input type="text" class="form-control" onkeypress='return AllowOnlyAmountAndDot(this,event,true);/>
function AllowOnlyAmountAndDot(id, e, decimalbool) {
if(decimalbool == true) {
var t = id.value;
var arr = t.split(".");
var lastVal = arr.pop();
var arr2 = lastVal.split('');
if (arr2.length > '2') {
e.preventDefault();
}
}
}
<input type="number" class="form-control" id="price" oninput="validate(this)" placeholder="Enter price" name="price" style="width:50%;">
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
On Input:
<input type="number" name="price" id="price" required>
On script:
$('#price').on('change', function() {
var get_price = document.getElementById('price').value;
var set_price = parseFloat(get_price).toFixed(2);
$('input[name=price').val(set_price);
})
You can use this. react hooks
<input
type="number"
name="price"
placeholder="Enter price"
step="any"
required
/>
just write
<input type="number" step="0.1" lang="nb">
lang='nb" let you write your decimal numbers with comma or period
On input:
step="any"
class="two-decimals"
On script:
$(".two-decimals").change(function(){
this.value = parseFloat(this.value).toFixed(2);
});

Prevent negative inputs in form input type="number"?

I want to restrict user input to positive numbers in an html form.
I know you can set min="0", however it is possible to bypass this by manually entering a negative number.
Is there any other way to solve this without writing a validation function?
This uses Javascript, but you don't have to write your own validation routine. Instead just check the validity.valid property. This will be true if and only if the input falls within the range.
<html>
<body>
<form action="#">
<input type="number" name="test" min=0 oninput="validity.valid||(value='');"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
This is not possible without validating the value of the input.
input type=number
The input element with a type attribute whose value is "number" represents a precise control for setting the element’s value to a string representing a number.
Since it is a string representing the number there is no way to be sure that string may be representing numeric values or not.
The Permitted attributes will not give you the ability to validate the value of the number input control.
One way to do this with the help of JavaScript could look like this.
// Select your input element.
var numInput = document.querySelector('input');
// Listen for input event on numInput.
numInput.addEventListener('input', function(){
// Let's match only digits.
var num = this.value.match(/^\d+$/);
if (num === null) {
// If we have no match, value will be empty.
this.value = "";
}
}, false)
<input type="number" min="0" />
If you are planing on sending your data to a server make sure to validate the data on the server as well.
Client side JavaScript can not ensure that the data that is being sent will be what you expect it to be.
If you want to ensure default value, i.e min value, or any other value, this is working solution. This is also preventing to clear the input field. Same way you can set to it's max value as well.
<input type="number" min="1" max="9999" maxlength="4" oninput="this.value=this.value.slice(0,this.maxLength||1/1);this.value=(this.value < 1) ? (1/1) : this.value;">
The following script will only allow numbers or a backspace to be entered into the input.
var number = document.getElementById('number');
number.onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8)) {
return false;
}
}
<input type="number" id="number" min="0">
type="number" already solves allowing numbers only to be typed as the other answers here point out.
Just for reference: with jQuery you can overwrite negative values on focusout with the following code:
$(document).ready(function(){
$("body").delegate('#myInputNumber', 'focusout', function(){
if($(this).val() < 0){
$(this).val('0');
}
});
});
This does not replace server side validation!
On html put onKeypress event listener
<input type="text" onkeypress="validate(event)">
write the validate function like this:
<script>
function validate(event) {
if (event.key == "-") {
event.preventDefault();
return false;
}
}
</script>
in case of angularjs pass $event in place of event, i have tested this in angularjs and in javascript
WAY 01:
Template:
<input name="price" type="number" (keydown)="onKeydown($event)" min="0" required />
file-name.ts:
onKeydown(event: KeyboardEvent): boolean {
if (!((event.keyCode > 95 && event.keyCode < 106)
|| (event.keyCode > 47 && event.keyCode < 58)
|| event.keyCode === 8)) {
return false;
}
return true;
}
WAY 02:
Template:
<input name="price" type="number" min="0" oninput="this.value = Math.abs(this.value)" required />
In HTML5, I like this way. Also it's much suitable with angular.
<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
Angular | Typescript Syntax
HTML:
<input type="number" (keydown)="onKeyDown($event)">
ts File:
onKeyDown(e:any):void{
if(!e)
return;
console.log('ee',e);
if((e.code==='Minus' && e.keyCode==189 && e.key==='-') || (e.keyCode==187 && e.key==='+')
||(e.code==='KeyE' && e.keyCode==69 && e.key==='e')){
e.preventDefault();
}
}
JavaScript Syntax
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h1>Create Account</h1>
<form id="user" name="user">
<div class="row">
<div class="col-6">
<label for="fname">First Name*</label>
<input type="number" id="fname" placeholder="Enter Your first name" required>
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$('#fname').keydown(function(e){
console.log('evt e.key:::::', e);
if(e.key=='-' && e.keyCode==189 || e.key=='+' && e.keyCode==187 )
{
e.preventDefault();
}
console.log('evt e.keyCode:::::', e.keyCode);
console.log('evt e.code:::::', e.code);
});
</script>