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 t
Did you try the property maxlength ?
<input type="text" maxlength="5" name="user" >
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>
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" />
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;
}
}
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;
}
}
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">