HTML attribute which excludes this value - javascript

" <input type="number" min="1" max="100"> *
...
I did not know how to exclude 0, so I set the minimum value to 1, Please help)

you cannot exclude via html syntax, you'd need javascript for that. the min value=1 might be the only way via html only.

You can use jquery like that:
$('input').keypress(function(e){
if (this.value.length == 0 && e.which == 48 ){
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" min="1" max="100">

As I understood from you question you want to exclude zero, which means all other numbers (< 100) are accepted
try this code: it accepts the negative numbers + positive numbers > 0 and =< 100
const input = document.querySelector("input")
input.addEventListener('change', function(e) {
if ( e.target.value === "0" ) {
input.value = 1
}
})
<input type="number" max="100"/>

Related

How can I validate that a number is entered into a text input with javascript? [duplicate]

I can't find the right regex pattern for this, even though there are a lot of questions in this kind.
I dont want the user to be able to type or input
<td><input type="number" pattern=" 0+\.[0-9]*[1-9][0-9]*$" name="itemConsumption" /></td>
-1.0 (Negative values)
String Values and any character
1.0 (Decimal Values)
No range Limit
I only want to accept positive whole numbers
SOLVED
no need for regex, I did not know this :D
<td><input type="number" pattern=" 0+\.[0-9]*[1-9][0-9]*$" name="itemConsumption" onkeypress="return event.charCode >= 48 && event.charCode <= 57"</td>
To disallow any input but numeric, you may use
<input type="text" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" name="itemConsumption" />
^------------....
<form id="mfrm">
<table>
<tr>
<td>Enter number only: <input type="text" name="itemConsumption" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" /></td>
<td><input type="Submit"/></td>
</tr>
</table>
Here, the event.charCode == 8 || event.charCode == 0 || event.charCode == 13 condition handles the case when DELETE, BACKSPACE or ENTER keys are pressed (important for Firefox, see Mohit's comment below and datashaman's comment related to enabling the ENTER key).
The event.charCode >= 48 && event.charCode <= 57 means that only 0 (decimal code 48) and all other digits up to 9 (decimal code 57) will be returned.
You can use type, min and oninput
<input type="number" min="0" step="1" oninput="validity.valid||(value='');">
<form>
<label>Input with positive numbers only</label><br/><br/>
<input type="number" min="0" step="1" oninput="validity.valid||(value='');">
</form>
I tried a lot of different solutions to achieve this, and I finally came up with this one, which does the job perfectly for us. It works for typing and for copy/paste, and I couldn't find any unwanted side-effects.
<form>
<input
type="number"
min="0"
step="1"
onfocus="this.previousValue = this.value"
onkeydown="this.previousValue = this.value"
oninput="validity.valid || (value = this.previousValue)"
/>
</form>
It is like Nikhil Mahirrao's solution, but it will cause invalid keystrokes to be simply ignored without emptying the input.
To allow only number values you can use as follows:
<td><input type="number" pattern="\d+" name="itemConsumption" /></td>
If it comes to HTML5 then you might try min attribute:
<input type="number" min="0">
You can use this regex pattern for whole numbers [0-9]* or \d*
[0-9] is range you can type 0 to 9 and * means not expecting any number or may you type infinite numbers
Maybe this jQuery Codepen snipet will be helpful for someone.
It's for type="number" (not "text"):
<input class="js-input-absint" type="number" step="1" min="18" max="150" name="age" value="50">
with [0-9] allowed inputs only. In the input will printed/pasted only numbers [0-9] with an min-max range (optional).
Some explanations: The code displays only numbers at the input stage, and does not reset the value to "" (empty) in case of inputting not valid number values like it does by default for type="number". And you can't use the attribute pattern="/^[0-9]*$/" for an input type="number".
var $inputAbsint = $('.js-input-absint');
if ($inputAbsint.length) {
$(document).on('keypress', '.js-input-absint', function (event) {
var allowed = /^[0-9]|Arrow(Left|Right)|Backspace|Home|End|Delete$/;
return allowed.test(event.key);
}).on('focusout paste', '.js-input-absint', function () {
var $input = $(this);
var defaultValue = this.defaultValue || $input.attr('min');
// Important(!): Timeout for the updated value
setTimeout(function () {
var current = $input.val();
var regexNumbers = new RegExp(/^[0-9]*$/, 'g');
var isNumbersOnly = regexNumbers.test(current);
// Clear wrong value (not numbers)
if ((current === '' || !isNumbersOnly) && defaultValue.length) {
$input.val(defaultValue);
current = defaultValue;
}
// Min/Max
var min = parseInt($input.attr('min'), 10);
var max = parseInt($input.attr('max'), 10);
var currentInt = parseInt(current, 10);
if (!isNaN(min) && !isNaN(currentInt) && currentInt < min) {
$input.val(min);
}
if (!isNaN(max) && !isNaN(currentInt) && currentInt > max) {
$input.val(max);
}
}, 100);
});
}
You can't press ' - ' button on keyboard.
<!--HTML Code is below-->
<input type="text" name="value1" id="value1" class="form-control" required="required" onkeyup="keyCode(event)">
<!--JQuery Code is below-->
<script>
$(document).ready(function() {
$value1.on("keyup", function keyCode(event){
var x = event.keyCode;
if (x == 109 || x == 189) {
event.preventDefault();
alert ("You can't enter minus value !");
}
});
});
</script>
Keycode of '109' represent numeric side minus button of keyboard. Keycode of '189' represent minus button above of the character buttons.
Nikhil Mahirrao answer is elegant and short!
I wanted something similar, however the field should not bounce back to an empty string, but in addition simply ignore any input that is not a number. Also, leading zeros should be filtered.
... oninput="filterNonNumbers(this)" ...
function filterNonNumbers(inputElement) {
let valOriginal = inputElement.value;
let valFiltered = valOriginal.split('').filter(c => c.charCodeAt(0) >= 48 && c.charCodeAt(0) <= 57 ? c : '').join('').replace(/^0+/, '');
if (valOriginal !== valFiltered) {
inputElement.value = valFiltered;
}
}
Of course, it works just like Nikhil's code when typing directly as well as when pasting via the clipboard.
Perhaps someone has a similar, extended requirement.
Just wanted to throw out a solution to round it off upon input.
<input id="numinput" type="number" step=1
oninput="validateWholeNmericInput('numinput', this.value)">
function validateWholeNumericInput(id, val){
if(!Number.isInteger(val)){
var newval = Math.round(val);
document.getElementById(id).value = newval;
}
}

Using Jquery to Limit an input field from -100 to 100

I am trying to limit a few input fields that would allow the user to input -100(min) and up to 100(max), while allow two decimal places. This one is tricky, so it should allow 99.99 but not allow 100.01. Also allow -99.99 but not -100.01, upon key-down it needs to remove what ever is wrong and prevent the user from entering an more characters If they hit -100 or 100 or -99.xx or 99.xx.
My code so far but is behaving very speraticly:
$(document).off('keyup keydown', 'input.NegativeHundredPercentMax');
$(document).on('keyup keydown', 'input.NegativeHundredPercentMax', function(e) {
var $myInput = $(this);
if ($myInput.val().length <= 4 ) {
if ($myInput.val() <= -101) {
e.preventDefault();
$myInput.val($myInput.val().slice(0, 3));
}
} else {
if ($myInput.val() <= -101) {
e.preventDefault();
$myInput.val($myInput.val().slice(0, 4));
}
}
});
you can do that using HTML5 something like this should help
<input type="number" name="quantity" min="-100" max="100" step="0.01">
HTML5 alone can handle an input which:
takes only numbers
has a minimum entry of -100
has a maximum entry of 100
increments in 100ths
This will do it:
<input type="number" name="myNumber" min="-100" max="100" step="0.01" value="1" />
Working Example:
<input type="number" name="myNumber" min="-100" max="100" step="0.01" value="1" />
I corrected the issue by removing all complexity.
$(document).off('keyup keydown', 'input.NegativeHundredPercentMax');
$(document).on('keyup keydown', 'input.NegativeHundredPercentMax', function(e) {
var $myInput = $(this);
if ($myInput.val() < -100) {
$myInput.val(-100);
}
if ($myInput.val() > 100) {
$myInput.val(100);
}
});

Disable multiple numbers after zero in input type="number"

This is my HTML:
<input type="number" min="0" oninput="validity.valid||(value='');" step="0.1"/>
However, I can still type something like:
0000 or 000111 or 00223, etc.
in my input field. How can I limit it only to one 0?
Is there a way to do this in HTML only?
Thanks.
Check if your input starts with zero and override next digits with only 0.
function checkZero(){
var val = document.getElementById("num").value;
if(val.startsWith("0")){
document.getElementById("num").value = "0";
}
}
<input id="num" type="number" min="0" oninput="checkZero()" step="0.1"/>
I'd go with something like this:
while (s.charAt(0) == '0') {
if (s.length == 1) { break };
if (s.charAt(1) == '.') { break };
s = s.substr(1, s.length-1)
}
It accepts numbers like 0.1 and handles 00.1 or 001.

How to set maximum length in input type=number? [duplicate]

This question already has answers here:
How can I set max-length in an HTML5 "input type=number" element?
(31 answers)
Closed last year.
I have a text field.
<input type="number" min="0" max="999">
But i am able to type as many numbers inside the text box.
As I set max=999, I don't want that to happen.
Anyone knows the solution for this?
I have tried ng-maxlength and maxlength but doesn't work.
max attribue specifies the maximum possible value that we can specify.
for more details see this link
I think the following will be helpful to you,
//maxlength="10"
<input type="number" onKeyPress="if(this.value.length==10) return false;" />
Try This
var jimApp = angular.module("mainApp", []);
jimApp.controller('mainCtrl', function($scope){
var oldNumber = 0;
$scope.numberChanged = function(number){
if(number<=999){
oldNumber = number;
}
return oldNumber;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
<input type="number" min="0" max="999" ng-model="jimNum" ng-change="jimNum = numberChanged(jimNum);">
</div>
The solution that worked for me is to use onkeypress with the max attribute.
For e.g. for max length of 999
<input type="number" max="999" onkeypress="if (this.value.length > 2) return false;"/>
Tested in Chrome, Firefox and Edge.
Try
<input type="number" min="0" max="999"
onKeyUp="if(this.value>999){this.value='999';}else if(this.value<0){this.value='0';}"
id="yourid">
There is JSFiddle, using JQuery.
Your input
<input type="number" id="num">
The script :
$("#num").keypress( function(e) {
var current_val = $(this).val();
var typing_char = String.fromCharCode(e.which);
if (parseFloat(current_val + "" +typing_char) > 900) {
return false;
}
})
if you are limit the single field
<TextField type="number"
className="text-field-amount"
onInput={(e)=>{
e.target.value = Math.max(0, parseInt(e.target.value) ).toString().slice(0,2)
}}
min={0}
if you are mapping more then one number Text field through map then do like this
<TextField
key={key}
label={row.q_desc}
type="number"
onChange={this.onChange}
onInput={this.onInput}
/>
onInput= event => {
event.preventDefault();
debugger;
var textField_name = this.state.input_Name;
if (textField_name == "Zip") {
event.target.value = Math.max(0, parseInt(event.target.value))
.toString()
.slice(0, 4);
}
if (textField_name == "Social Security") {
event.target.value = Math.max(0, parseInt(event.target.value))
.toString()
.slice(0, 9);
}
if (textField_name == "Phone") {
event.target.value = Math.max(0, parseInt(event.target.value))
.toString()
.slice(0, 10);
}
};
onChange(e) {
debugger;
this.setState({
input_Name: e.target.name
});
}

Limit number of characters in input type number

Im trying to limit to X number the characters in a input (type of number). ive tried a lot of options and none seems to work. I dont want to use the option tel as it needs the numeric keyboard on a mobile device (yes, with ., and all the symbols) I tried also the pattern solution but it only worked for iOS, didnt work in android (displayed the normal keyboard).
The best way would be that if the user hits the limit dont let him type anymore, if he wants to highlight the text and re-type a different number he is allow to. Just not let him type more than the specified number of characters.
So, any help is appreciated.
Note: charCode is non-standard and deprecated, whereas keyCode is simply deprecated.
Check this code
JavaScript
<script>
function check(e,value)
{
//Check Charater
var unicode=e.charCode? e.charCode : e.keyCode;
if (value.indexOf(".") != -1)if( unicode == 46 )return false;
if (unicode!=8)if((unicode<48||unicode>57)&&unicode!=46)return false;
}
function checkLength()
{
var fieldLength = document.getElementById('txtF').value.length;
//Suppose u want 4 number of character
if(fieldLength <= 4){
return true;
}
else
{
var str = document.getElementById('txtF').value;
str = str.substring(0, str.length - 1);
document.getElementById('txtF').value = str;
}
}
and HTML input with number type below
onInput //Is fired also if value change from the side arrows of field in Chrome browser
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength()" />
Fiddle Demo
Update -- Little bit generic code example
Change above function into this one
function checkLength(len,ele){
var fieldLength = ele.value.length;
if(fieldLength <= len){
return true;
}
else
{
var str = ele.value;
str = str.substring(0, str.length - 1);
ele.value = str;
}
}
In HTML use like this
<!-- length 4 -->
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength(4,this)" />
<!-- length 5 -->
<input type="number" onKeyPress="return check(event,value)" onInput="checkLength(5,this)" />
<!-- length 2 -->
<input type="number" onKeyPress="return check(event,value)" onInput="checkLength(2,this)" />
Demo
Another option - the tel input type abides by the maxlength and size attributes.
<input type="tel" size="2" maxlength="2" />
<input type="tel" size="10" maxlength="2" />
May be it will be useful.
Here is field to input Patient Age. It allows to input 3 numbers only.
HTML
<input autocomplete="off" class="form-control" id="Patient_Age" max="150" maxlength="3" name="PatientAge" placeholder="Age" size="3" type="number" value="0">
JS
<script>
$(function () {
$("#Patient_Age").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter
if ($(this).val().length <= 2 || $.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A
// (e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
event.preventDefault();
}
// Ensure that it is a number and stop the keypress
if ($(this).val().length <= 2 || (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
else {
event.preventDefault();
}
});
}); // end of $
</script>
The HTML5 number type input has min and max attributes.
If you wanted to limit the number of characters to 1 you could set a min of 0 and a max of 9.
You can also set the step attribute, which is 1 by default, but would come in use if you wanted the ability to select decimals or other rounded numbers.
<input type="number" maxlength="1" max="9" min="1" size="1" />
Here's the full demo
please review this code
<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
} else {
limitCount.value = limitNum - limitField.value.length;
}
}
</script>
<form name="myform">
<input name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,this.form.countdown,15);"
onKeyUp="limitText(this.form.limitedtextfield,this.form.countdown,15);" maxlength="15"><br>
<font size="1">(Maximum characters: 15)<br>
You have <input readonly type="text" name="countdown" size="3" value="15"> characters left.</font>
</form>
I think this requires the onkeyup event handler.
Use this handler to keep on entering numbers till 5 keyup's are encountered. After this , don't let the the number to be entered by returning a 0, unless key pressed is backspace or delete .
You can try thiss jQuery code :
In HTML
<input type="number" id="number" />
In JS
$(document).ready(function () {
var element = document.getElementById('number');
$("#number").keydown(function (event) {
// Allow only backspace and delete
if($(this).val().length <= 9 || event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 )
{
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
// let it happen, don't do anything
} else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
}
}else{
event.preventDefault();
}
});
});
I have not any idea wheather its working on IOS N Android but its work on all browser.
DEMO
For Decimal values, lets say "25.2" code is as under.
if(thisObj.value.indexOf(".") >=0)
{
if(fieldLength <= 4)
{
return true;
}
else
{
var str = thisObj.value;
str = str.substring(0, str.length - 1);
thisObj.value = str;
}
}
else
{
if(fieldLength <= 2)
{
return true;
}
else
{
var str = thisObj.value;
str = str.substring(0, str.length - 1);
thisObj.value = str;
}
}
You can easily do it like this,
<input type="text" pattern="\d*" maxlength="4">
Proper way 2020 for type number is to check on keydown validation and it should work like this: onkeypress="checkValidation(fieldValue);" <-- on input in html and in js:
checkValidation(a) {
if (`${a}`.length < 8) {
return true;
} else {
return false;
}
}
Use the maxlength property like this.
<input type="text" maxlength="5"/>
Dude why go for javascript? Just try
<input type="text" maxlength="4" size="4">
maxlength will anyways define a maximum length for the input field.
Hope this solved the problem :)
EDIT: Since you specifically want numbers, why dont you use the above and then run a jquery validation to check for numbers? That will also work..
EDIT: Okay, try
<input type="number" name="pin" min="1000" max="9999">
Did you try the property maxlength ?
<input type="text" maxlength="5" name="user" >

Categories

Resources