Limit the user's input in an input number to 4 digits - javascript

How can I prevent (usign maybe Angular) the user from entering more than 4 numbers in a an simple number like this one :
<input type="number">
I used ng-maxlength, and max attributes, but those attributes as specified by w3.org specs and the official website Angular, do not prevent the user from adding more numbers.
What I want is that the input stops in 4 digits, like adding in somehow a mask or something to it.

Here is a way to do it using JavaScript:
HTML
<input type="number" oninput="checkNumberFieldLength(this);">
JavaScript
function checkNumberFieldLength(elem){
if (elem.value.length > 4) {
elem.value = elem.value.slice(0,4);
}
}
I would also suggest to make use of the min and max HTML attributes for the input Number element, if it applies in your case.
JSFiddle
W3c: input Number

Well, as somebody stated above maxlength doesn't work with inputs of type number, so you can do it this way:
<input type="text" pattern="\d*" maxlength="4">
of course, this will do if it's not a requirement to have input type="number"

Using ng-pattern with a regex
\d : digits
{4} : 4 times
<input type="number" ng-pattern="/^\d{4}$/" />

I would create a function in your controller like this
angular.module("my-app", [])
.controller('my-controller', function($scope) {
$scope.checkInput = function() {
if (input.value.length > 4) {
input.value = input.value.slice(0,4);
}
});
});
Then in your view you can do something like this
<input type="number" max="9999" ng-input="checkInput()" />
Warning: The max attribute will only work for the spinner. The user will still be able to enter numbers higher than that. Here's an example
<input type="number" max="9999" />

You can do that using modernizr and jquery.
I've made an example here: https://jsfiddle.net/5Lv0upnj/
$(function() {
// Check if the browser supports input[type=number]
if (Modernizr.inputtypes.number) {
$('input[type=number]').keypress(function(e) {
var $this = $(this),
maxlength = $this.attr('maxlength'),
length = $this.val().length;
if (length >= maxlength)
e.preventDefault();
});
}
});

Related

How to force the user to put only numbers

I want the user to only be able to use input for numbers I've tried several things like oninput="this.value = this.value.replace(/[^0-9.]/g, '') and a lot more but for example the code I sent if I type a letter and keep pressing the letter on the keyboard it won't turn it to anything, I need a code that will 100% force the user to type only numbers doesn't matter what happens. if I could put a number in the input box that the user cant delete for example 0 it will be good to.
There are a few different ways to accomplish this but one of them would be capturing the keypress itself and returning false if the input is not a number.
Also if I understand you correctly, to add a default value of "0", just define it in the input directly like value="0", or you could use a placeholder="0" if that's what you're looking for.
<input type="number" value="0" onkeydown="javascript: return event.keyCode === 8 || event.keyCode === 46 ? true : !isNaN(Number(event.key))" />
You can use <input type=...> as mentioned in the input specification.
While this wouldn't enforce the user input to numbers only, you may want to consider using the pattern attribute to leverage some built-in behaviour. If you type non-numeric characters, the text colour will turn red:
input:invalid {
color: red;
}
<input type="text" pattern="[0-9]+"/>
Then we can start looking at the constraint validation API:
The Constraint Validation API enables checking values that users have entered into form controls, before submitting the values to the server.
If you type non-numeric characters and try to submit the form, you should see a built-in tooltip displaying a custom error message:
const input = document.querySelector('input');
input.addEventListener('invalid', () => {
if (input.validity.patternMismatch) {
input.setCustomValidity('Numbers only please!!');
}
});
input:invalid {
color: red;
}
<form>
<input type="text" pattern="[0-9]+"/>
<button type="submit">submit</button>
</form>
$("#but").click(function(){
let inp_val = $("#txt").val();
if(isNaN(inp_val)){
alert("Just enter a number.");
$("#txt").val("");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt">
<input type="button" value="CLICK" id="but">

Disable user of multiple same exact numbers in input box

I have an input box here
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" >
And I want to disallow users to enter the same numbers in the box? How can I do this ? Thanks in advance
I don't want them to be able to enter numbers like this
111111111
or
55555555
You can use a regular expression to find strings that only consist of one consecutive digit:
var validator = /\b(\d)\1+\b/
console.log(validator.test('111')) // true
console.log(validator.test('123')) // false
console.log(validator.test('121')) // false
console.log(validator.test('112')) // false
#edit If you don't want to let user enter these values as he types you may want to verify only when value equals to 2.
You can listen on keydown event of input element and verify it's actual content and pressed number like this:
var inputNode = document.getElementById('my_account');
inputNode.addEventListener('keydown', (event) => {
var inputValue = event.key;
var inputNodeValue = inputNode.value;
var length = inputNodeValue.length;
if (length === 1 && inputNodeValue[0] === inputValue) {
event.preventDefault();
}
});
If you want to verify on submit, just get value of first character and check if every other is equal to it.
Try this pattern:
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" pattern="^(?!(\d)\1{8}).*">
Notes:
you did not say you wanted to disallow letters, if you do, just replace .* with \d*
I interpreted it as "nine times the same number". If you want to e.g. not allow "3 times same number anywhere", you need to change it to ^(?!\d*(\d)\1{2,}).*
If you want to only disallow multiples of a digit without any other extra, add the line termination regex: ^(?!(\d)\1*$).*
Example for "not 3 times same number anywhere but must be numbers":
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" pattern="^(?!\d*(\d)\1{2,})\d*">
Example for "not only the same number multiple times but still numbers":
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" pattern="^(?!(\d)\1*$)\d*">

Why 1. returns an empty string when I try to get value of an input type number using javascript and html5?

I have a normal input as follows:
<input type="number" name="quantity" id="myInput">
If I type "1." (without the quotes of course) when I try to get the value of the input with
document.getElementById("myInput").value
Only an empty string is obtained.
Is there any other way to get the "1." input with javascript?
Edit
I am working using Polymer 1.0 and databinding, so in my example I showed using normal JavaScript syntax with the intention of finding a solution to my problem using only javascript.
I just want to know how to access a property that returns the value of the input, and which I believe should be stored in some property of the object.
If you use <input type="number"> the element is enriched with an extra attribute, valueAsNumber. So instead of
document.getElementById("myInput").value
use
document.getElementById("myInput").valueAsNumber
valueAsNumber will return NaN instead of blank if the value entered in the input not is convertable to a number. There is also a validity attribute holding information of the status of the current value, both according to the value as supposed number but also according to the number input's settings, i.e "why is the number invalid".
Fun with number inputs, try this out in various browsers :
<input type="number" name="quantity" id="myInput" ><br>
<input type="text" id="value" ><br>
<input type="text" id="valueAsNumber" ><br>
<input type="text" id="validity" ><br>
document.getElementById("myInput").onkeyup = function() {
document.getElementById("value").value = this.value;
document.getElementById("valueAsNumber").value = this.valueAsNumber;
document.getElementById("validity").value = '';
for (validity in this.validity) {
if (this.validity[validity]) {
document.getElementById("validity").value+=validity+' ';
}
}
}
actually quite informative, if you want to investigate exactly why you get an empty value back from the input -> http://jsfiddle.net/oaewv2Lr/ Have tried with Chrome, Opera and FF - Chrome seems to be the most "forgiving" browser of those three.
I found a way to get invalid values:
Focus the input.
Select its contents using execCommand().
Grab the selection using window.getSelection().
Example:
document.querySelector('input[type="submit"]').addEventListener('click', function() {
var inp= document.getElementById('myInput');
inp.focus();
document.execCommand('SelectAll');
var value = window.getSelection().toString();
document.getElementById('output').textContent = value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="quantity" id="myInput">
<input type="submit">
<div id="output"></div>
It won't work if you will enter 1., as 1. is not a valid number.
Update: It seems that your use of type="number" means that certain values won't come back. You can switch it to a type="text" and do the checking yourself:
document.getElementById('mySubmit').addEventListener('click', function() {
var value = document.getElementById('myInput').value;
if ( value != parseFloat(value) )
alert('Invalid Number');
document.getElementById('myOutput').innerHTML = value;
});
<input type="text" name="quantity" id="myInput">
<input type="submit" id="mySubmit">
<div id="myOutput"></div>

Custom Validation on HTML Number Input Misbehaving

In putting together a small webapp, I'm trying to ensure that end users are unable to place invalid characters in a number field that can hold signed floats. I'm using Dojo to search on an applied CSS class (in this case, ogInputNumber) and set events on input, keyup, and blur.
Ideally, I would like the input to be type="number" and to only allow digits, a hyphen (for signed floats), and a period character to act as a decimal place. If a user includes more than one hyphen or period character, the JS should truncate that second invalid character and everything thereafter in the input. Unfortunately, the JS behaves differently depending on whether the input is type="number" or type="text".
For type="text", if I attempt to enter the text 2.6a, 2.6 is fine, but the a is caught on the input event and prevented from appearing in the input. This is the desired behavior, but I would like to have the input as type="number" so the number spinners appear and for ease of use with mobile devices (so the number keyboard is brought up by default).
For type="number", if I attempt to enter the text 2.6a, the 2.6 is allowed to remain, but as soon as a is typed, the entire field is cleared out. That will prevent any invalid characters, but it's annoyingly overzealous. I've replicated this behavior on Chrome, Firefox, IE11, and Opera.
Can anyone offer any suggestions as to why the JS operates differently between inputs with type="text" and those with type="number"?
HTML:
<p>
<label for="numberInput1">Text Input</label>
<input id="numberInput1" class="ogInputNumber" type="text" />
</p>
<p>
<label for="numberInput2">Number Input</label>
<input id="numberInput2" class="ogInputNumber" type="number" />
</p>
JS:
// Checks number input fields for proper formatting
require(["dojo/domReady!", "dojo/on", "dojo/query"],
function (ready, on, query) {
query(".ogInputNumber").forEach(function (node) {
// Replace all the non-numeric, non-period, and non-hyphen characters with nothing while the user is typing
on(node, "input, keyup", function () {
this.value = this.value.replace(/[^\d\.-]/g, '');
});
// When the user leaves the input, format it properly as a signed float (or zero if it's something weird)
on(node, "blur", function () {
try {
if (this.value) {
this.value = parseFloat(this.value).toString();
} else {}
} catch (error) {
this.value = 0;
}
});
});
});
Working JSFiddle: http://jsfiddle.net/etehy6o6/1/
I think that's the default behavior of number input type, but I'm not sure. It's logical to think the input should not let the user put anything that is not a number, so it clears all the value before you can fire your keyup event.
So to keep the last valid value declare a variable outside the scope of your event and set it to the replaced value that was not cleared because invalid key input.
Using the code in your Fiddle:
Edited because addressed bug in comments
HTML
<!-- I asigned default values to test other scenarios -->
<p>
<label for="numberInput1">Text Input</label>
<input id="numberInput2" class="ogInputNumber" type="text" value="3.1416" />
</p>
<p>
<label for="numberInput">Number Input</label>
<input id="numberInput" class="ogInputNumber" type="number" value="3.1416" />
</p>
Javascript
// Checks number input fields for proper formatting
require(["dojo/domReady!", "dojo/on", "dojo/query"],
function (ready, on, query) {
query(".ogInputNumber").forEach(function (node) {
var validValue = this.value;
// Replace all the non-numeric, non-period, and non-hyphen characters with nothing while the user is typing
on(node, "input, keyup", function () {
if (this.value == '' && validValue.length > 1) {
this.value = validValue;
}
this.value = this.value.replace(/[^\d\.-]/g, '');
validValue = this.value;
});
// When the user leaves the input, format it properly as a signed float (or zero if it's something weird)
on(node, "blur", function () {
try {
if (this.value) {
this.value = parseFloat(this.value).toString();
} else {}
} catch (error) {
this.value = 0;
}
});
});
});

I have issues with my JavaScript

I don't what happen with my script can i please point out where is my mistake. 1 to 9 all condition working fine but when you put 10-12 is not work
<form method="post" enctype="multipart/form-data" action="#">
<input type="hidden" value="2" id="itemstock" name="itemstock">
<input value="1" name="quantity" id="quantity" class="text">
<button type="submit" onClick="return checkoption();" >Click </button>
</form>
Javascript
function checkoption()
{
var itemqty = document.getElementById('quantity');
var iss = document.getElementById('itemstock');
if(itemqty.value > iss.value)
{
alert('We have Currently '+iss.value+' In Stock');
}
else
{
alert('add to cart');
}
}
Thank you in advance
Screen short see qty i put 13 but its not showing error
Using the < or > operators with strings will compare the values alphabetically, which is probably not what you want.
You need to compare these as numbers, not as strings. JavaScript allows you to easily cast a string to a number using +, like so:
var qty = +itemqty.value;
var isv = +iss.value;
if(qty > isv)
{
// ...
}
However, you can also use parseInt (which will return NaN if the value is invalid) if you want to add more error checking in your code.
The .value attribute on a text field such as input is a string, not a number. Therefore, you compare strings lexicographically. Change them into numbers, either via parseInt(str, 10) or via +str.

Categories

Resources