Check html input before it's updated - html

I'm trying to implement a time picker in Angular, and I'm having some trouble figuring out how to check if the text input is valid.
In the html I have an input element that binds to keyPress function.
<input matInput style="text-align: right;" [(ngModel)]="hour" type="number" min="0" max="23" (keypress)="keyPress($event)">
keyPress(event: any) {
const pattern = /^(([[0|1]\d)|(2[0-3]))$/;
let inputChar = String.fromCharCode(event.charCode);
let tempHour = this.hour;
if (!tempHour) {
tempHour = '0';
}
let newHour = (+tempHour * 10 + +inputChar).toString();
if (newHour.length === 1) {
newHour = '0' + newHour;
}
if (!pattern.test(newHour)) {
event.preventDefault();
}
}
The problem here is that the event passed to the keyPress function only contains the current pressed key. This works fine unless the user moves the input cursor. For example: If user presses key "1", and then moves the cursor backwards and enter a "9". My code will treat it as 19 and let it pass, but the actual input is 91. So I guess I need to some how get the cursor position? Or is there a better way to solve this?
Thanks very much!

The problem is that the keypress-event happens before ngModel updates your "hour" variable. In your case I'd suggest to react on the change-event which gets fired after ngModel has already done its update.
(change)="onChange($event)"
And then your method can look like this
<input matInput style="text-align: right;" [(ngModel)]="hour" type="number" min="0" max="23" (change)="onChange($event)">
private lastValue: number = 0;
onChange(event: any) {
const pattern = /^(([[0|1]\d)|(2[0-3]))$/;
if (!pattern.test(this.hour)) {
this.hour = this.lastValue;
} else {
this.lastValue = this.hour;
}
}

Related

how frequently pattern attribute will be validating the text entered in html input

when i am doing a input field validation using pattern , how frequently the value will be validated . i would like to know whether it will validate on (keyup) or (change)
for ex:
<input type="email" [(ngModel)]="emailAddress" name="emailAddress" data-toggle="tooltip"
title="{{emailAddress}}" #email="ngModel" multiple
pattern="^(([a-zA-Z0-9_,.]*#*\w+([-+.']\w+)*\w+([-.]\w+)*\.\w+([-.]\w+)*)*([' '])*)*$"
class="form-control" />
i would like to know whether the text i enter will be validated on each keystroke ?
The pattern attribute is checked only upon submission the form or when you press enter on the input tag, so only on the enter key's stroke you might say.
If you want it to be validated on every keypress, keyup or onchange, you can set the corresponding attribute to validate the input like so:
<input keyup="validate(this)" />
...
<script>
function validate(x)
{
regex = /[a-zA-Z0-9]+/;
window.alert(x.value.match(regex) == null);
}
</script>
If I understand correctly your issue, you are trying to check the value entered "real time".
In the case, you could use input event to get value changed.
// Add error message element after input.
$('#input_email').after('<span class="error-message">Please write your message error here!</span>')
$('#input_email').on('input', function (evt) {
var $regex=/^(([a-zA-Z0-9_,.]*#*\w+([-+.']\w+)*\w+([-.]\w+)*\.\w+([-.]\w+)*)*([' '])*)*$/;
var value = evt.target.value;
if (value.length === 0) {
evt.target.className = ''
return
}
var result = value.match($regex);
if (result) {
evt.target.className = 'valid'
} else {
evt.target.className = 'invalid'
}
})
input.invalid + .error-message {
display: initial;
}
.error-message {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input_email" type="email" [(ngModel)]="emailAddress" name="emailAddress" data-toggle="tooltip"
title="{{emailAddress}}" #email="ngModel" multiple
pattern="^(([a-zA-Z0-9_,.]*#*\w+([-+.']\w+)*\w+([-.]\w+)*\.\w+([-.]\w+)*)*([' '])*)*$"
class="form-control" />

Get the radio button value in a form [duplicate]

I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button (which one is selected) and return it to a variable. For some reason it keeps returning undefined.
Here is my code:
function findSelection(field) {
var test = 'document.theForm.' + field;
var sizes = test;
alert(sizes);
for (i=0; i < sizes.length; i++) {
if (sizes[i].checked==true) {
alert(sizes[i].value + ' you got a value');
return sizes[i].value;
}
}
}
submitForm:
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
}
HTML:
<form action="#n" name="theForm">
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked> Male
<input type="radio" name="genderS" value="0" > Female<br><br>
Search
</form>
This works with any explorer.
document.querySelector('input[name="genderS"]:checked').value;
This is a simple way to get the value of any input type.
You also do not need to include jQuery path.
You can do something like this:
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked="checked">Male</input>
<input type="radio" name="genderS" value="0">Female</input>
jsfiddle
Edit: Thanks HATCHA and jpsetung for your edit suggestions.
document.forms.your-form-name.elements.radio-button-name.value
Since jQuery 1.8, the correct syntax for the query is
$('input[name="genderS"]:checked').val();
Not $('input[#name="genderS"]:checked').val(); anymore, which was working in jQuery 1.7 (with the #).
ECMAScript 6 version
let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;
Here's a nice way to get the checked radio button's value with plain JavaScript:
const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');
// log out the value from the :checked radio
console.log(checked.value);
Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons
Using this HTML:
<form name="demo">
<label>
Mario
<input type="radio" value="mario" name="characters" checked>
</label>
<label>
Luigi
<input type="radio" value="luigi" name="characters">
</label>
<label>
Toad
<input type="radio" value="toad" name="characters">
</label>
</form>
You could also use Array Find the checked property to find the checked item:
Array.from(form.elements.characters).find(radio => radio.checked);
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:
var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);
or simpler:
alert(document.theForm.genderS.value);
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Edit:
As said by Chips_100 you should use :
var sizes = document.theForm[field];
directly without using the test variable.
Old answer:
Shouldn't you eval like this ?
var sizes = eval(test);
I don't know how that works, but to me you're only copying a string.
Try this
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert(sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
return false;
}
A fiddle here.
This is pure JavaScript, based on the answer by #Fontas but with safety code to return an empty string (and avoid a TypeError) if there isn't a selected radio button:
var genderSRadio = document.querySelector("input[name=genderS]:checked");
var genderSValue = genderSRadio ? genderSRadio.value : "";
The code breaks down like this:
Line 1: get a reference to the control that (a) is an <input> type, (b) has a name attribute of genderS, and (c) is checked.
Line 2: If there is such a control, return its value. If there isn't, return an empty string. The genderSRadio variable is truthy if Line 1 finds the control and null/falsey if it doesn't.
For JQuery, use #jbabey's answer, and note that if there isn't a selected radio button it will return undefined.
First, shoutout to ashraf aaref, who's answer I would like to expand a little.
As MDN Web Docs suggest, using RadioNodeList is the preferred way to go:
// Get the form
const form = document.forms[0];
// Get the form's radio buttons
const radios = form.elements['color'];
// You can also easily get the selected value
console.log(radios.value);
// Set the "red" option as the value, i.e. select it
radios.value = 'red';
One might however also select the form via querySelector, which works fine too:
const form = document.querySelector('form[name="somename"]')
However, selecting the radios directly will not work, because it returns a simple NodeList.
document.querySelectorAll('input[name="color"]')
// Returns: NodeList [ input, input ]
While selecting the form first returns a RadioNodeList
document.forms[0].elements['color']
// document.forms[0].color # Shortcut variant
// document.forms[0].elements['complex[naming]'] # Note: shortcuts do not work well with complex field names, thus `elements` for a more programmatic aproach
// Returns: RadioNodeList { 0: input, 1: input, value: "red", length: 2 }
This is why you have to select the form first and then call the elements Method. Aside from all the input Nodes, the RadioNodeList also includes a property value, which enables this simple manipulation.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Here is an Example for Radios where no Checked="checked" attribute is used
function test() {
var radios = document.getElementsByName("radiotest");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select Radio");
}
}
DEMO : http://jsfiddle.net/ipsjolly/hgdWp/2/ [Click Find without selecting any Radio]
Source (from my blog): http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html
Putting Ed Gibbs' answer into a general function:
function findSelection(rad_name) {
const rad_val = document.querySelector('input[name=' + rad_name + ']:checked');
return (rad_val ? rad_val.value : "");
}
Then you can do findSelection("genderS");
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.
I realize this is extremely old, but it can now be done in a single line
function findSelection(name) {
return document.querySelector(`[name="${name}"]:checked`).value
}
I prefer to use a formdata object as it represents the value that should be send if the form was submitted.
Note that it shows a snapshot of the form values. If you change the value, you need to recreate the FormData object. If you want to see the state change of the radio, you need to subscribe to the change event change event demo
Demo:
let formData = new FormData(document.querySelector("form"));
console.log(`The value is: ${formData.get("choice")}`);
<form>
<p>Pizza crust:</p>
<p>
<input type="radio" name="choice" value="regular" >
<label for="choice1id">Regular crust</label>
</p>
<p>
<input type="radio" name="choice" value="deep" checked >
<label for="choice2id">Deep dish</label>
</p>
</form>
If it is possible for you to assign a Id for your form element(), this way can be considered as a safe alternative way (specially when radio group element name is not unique in document):
function findSelection(field) {
var formInputElements = document.getElementById("yourFormId").getElementsByTagName("input");
alert(formInputElements);
for (i=0; i < formInputElements.length; i++) {
if ((formInputElements[i].type == "radio") && (formInputElements[i].name == field) && (formInputElements[i].checked)) {
alert(formInputElements[i].value + ' you got a value');
return formInputElements[i].value;
}
}
}
HTML:
<form action="#n" name="theForm" id="yourFormId">
I like to use brackets to get value from input, its way more clear than using dots.
document.forms['form_name']['input_name'].value;
var value = $('input:radio[name="radiogroupname"]:checked').val();

retrieving value of dynamically built set of checkboxes

I have a set of dynamically built checkboxes (sub-categories of main-category).
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001700">first</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001800">second</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001900">third</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18002000">forth</input>
Now when I submit the form, when I return back to the form from Server (if didn't pass validation, for example) I would like to be able to reconstruct that list of checkboxes with their values. Assume that the first two checkboxes were checked by the user I would like to have something like this:
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001700" checked>first</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001800" checked>second</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001900">third</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18002000">forth</input>
I assume that I do that as one of the first things here:
(document).ready(function () {
loadSubCategories();
}
I am using ASP.NET MVC and I can't figure out how do I deliver that information into the View (the HTML). I assume this is a common task in web development. How is it done in general?
You can use the localStorage provided by the web browser to store javascript variables to save the states of the checkbox and restore the states when teh webpage is loaded again.
This is how I did it:
function save() {
var elems = document.getElementsByName("SubCats");
var states = [];
for (i = 0; i < elems.length; i++) {
states.push(elems[i].checked);
}
localStorage.setItem("checkboxStates", JSON.stringify(states));
}
function restore() {
if (localStorage.getItem("checkboxStates") !== null) {
var states = JSON.parse(localStorage.getItem("checkboxStates"));
var elems = document.getElementsByName("SubCats");
for (i = 0; i < elems.length; i++) {
elems[i].checked = states[i];
}
}
}
restore();
Here is the JSFiddle demo
In the demo, you can check any checkbox you like and click the Save states button. When you re run the code, you will see that it keeps the previous settings.
The flow:
When you click the Save states button, the save() function is called and it builds an array of the checkbox states sequentially and serializes them before storing them in the localStorage.
When the page is loaded again, the restore() function is triggered by default. This checks if there are states saved before. And if there are, it deserializes then and then loops through the available checkboxes, setting the states back as previously saved.
Also note that the info stored in the localStorage can be accessed on any page and therefore the data is always available.
You can also read about sessionStorage.
Thank you all for all the help. These are all interesting suggestions, especially the one using localStorage which I have never used and perhaps I should give it a look.
Anyway, I decided to go for the naive way. I am keeping the checked Sub-Categories in a hidden text field separated by commas and then when building the tag again I am checking for every Sub-Category whether it has been checked before.
Here is my code:
function loadSubCategories() {
if ($("#ddlCategory").val() != "-1") {
var SubCatsCheckboxes = {};
SubCatsCheckboxes.url = "/BLHelpers/GetSubCats";
SubCatsCheckboxes.type = "POST";
SubCatsCheckboxes.data = JSON.stringify({ CategoryId: $("#ddlCategory").val() });
SubCatsCheckboxes.datatype = "json";
SubCatsCheckboxes.contentType = "application/json";
SubCatsCheckboxes.success = function (SubCatsList) {
var sub_cats = $("#SubCatsStr").val().split(",");
$("#SubCatsDiv").empty();
$.each(SubCatsList, function (index, value) {
var option_to_append = "<input type=\"checkbox\" name=\"SubCats\" class=\"subcat-checkbox\" value=\"" + value.SubCategoryId + "\"";
if ($.inArray(value.SubCategoryId.toString(), sub_cats) != -1) {
option_to_append += " checked "
}
option_to_append += ">" + value.Caption + "</option><br/>";
$("#SubCatsDiv").append(option_to_append);
});
};
$.ajax(SubCatsCheckboxes);
}
else {
$("#SubCatsDiv").empty();
}
}
Where :
<input id="SubCatsStr" name="SubCatsStr" type="hidden" value="#Model.SubCatsStr" />
is my hidden field that keeps the checked Sub Categories ids.

prevent cursor moving on text input

I have a few text inputs that I call a JS function when they are on focus. Basically this function changes the value oh this field.
When I do that, on IE, the cursor is moved to the left end of my input. That does not happen in Firefox. It just stays where I put it on the first place.
<input maxlength="5" type="text" onFocus=\"changeValueOnFocus(this);\">";
function changeValueOnFocus(myInput){
myInput.value = 1234;
}
Is there a way to avoid this?
Thanks!
Instead of onfocus rather use onfocusin, that'll make your code to work.
EDIT
I just realized, that there is no focusin in Firefox. Hence you need something heavier.
The script:
function changeValueOnFocus (e, elm) {
elm = elm || this;
elm.value = 1234;
return;
}
window.onload = function () {
if (window.onfocusin === undefined) {
document.getElementById('someinput').addEventListener('focus', changeValueOnFocus, false);
}
return;
}
and for input you'll need an id:
<input id="someinput" maxlength="5" onfocusin="changeValueOnFocus(event, this);" type="text" />
Now this supposed to be a cross-browser solution.
to move the cursor to the end of the textbox
modify your function like this :
function changeValueOnFocus(myInput) {
myInput.value = 1234;
//use this function to select text but in this case just to move cursor to the end
myInput.setSelectionRange(myInput.value.length, myInput.value.length);
}

How can I set max-length in an HTML5 "input type=number" element?

For <input type="number"> element, maxlength is not working. How can I restrict the maxlength for that number element?
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" />
The above will still not stop a user from manually entering a value outside of the specified range. Instead he will be displayed a popup telling him to enter a value within this range upon submitting the form as shown in this screenshot:
You can specify the min and max attributes, which will allow input only within a specific range.
<!-- equivalent to maxlength=4 -->
<input type="number" min="-9999" max="9999">
This only works for the spinner control buttons, however. Although the user may be able to type a number greater than the allowed max, the form will not submit.
Screenshot taken from Chrome 15
You can use the HTML5 oninput event in JavaScript to limit the number of characters:
myInput.oninput = function () {
if (this.value.length > 4) {
this.value = this.value.slice(0,4);
}
}
If you are looking for a Mobile Web solution in which you wish your user to see a number pad rather than a full text keyboard. Use type="tel". It will work with maxlength which saves you from creating extra javascript.
Max and Min will still allow the user to Type in numbers in excess of max and min, which is not optimal.
You can combine all of these like this:
<input name="myinput_drs"
oninput="maxLengthCheck(this)"
type = "number"
maxlength = "3"
min = "1"
max = "999" />
<script>
// This is an old version, for a more recent version look at
// https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/
function maxLengthCheck(object)
{
if (object.value.length > object.maxLength)
object.value = object.value.slice(0, object.maxLength)
}
</script>
Update:
You might also want to prevent any non-numeric characters to be entered, because object.length would be an empty string for the number inputs, and therefore its length would be 0. Thus the maxLengthCheck function won't work.
Solution:
See this or this for examples.
Demo - See the full version of the code here:
http://jsfiddle.net/DRSDavidSoft/zb4ft1qq/1/
Update 2: Here's the update code:
https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/
Update 3:
Please note that allowing more than a decimal point to be entered can mess up with the numeral value.
Or if your max value is for example 99 and minimum 0, you can add this to input element (your value will be rewrited by your max value etc.)
<input type="number" min="0" max="99"
onKeyUp="if(this.value>99){this.value='99';}else if(this.value<0){this.value='0';}"
id="yourid">
Then (if you want), you could check if is input really number
it's very simple, with some javascript you can simulate a maxlength, check it out:
//maxlength="2"
<input type="number" onKeyDown="if(this.value.length==2) return false;" />
You can specify it as text, but add pettern, that match numbers only:
<input type="text" pattern="\d*" maxlength="2">
It works perfect and also on mobile ( tested on iOS 8 and Android ) pops out the number keyboard.
Lets say you wanted the maximum allowed value to be 1000 - either typed or with the spinner.
You restrict the spinner values using:
type="number" min="0" max="1000"
and restrict what is typed by the keyboard with javascript:
onkeyup="if(parseInt(this.value)>1000){ this.value =1000; return false; }"
<input type="number" min="0" max="1000" onkeyup="if(parseInt(this.value)>1000){ this.value =1000; return false; }">
//For Angular I have attached following snippet.
<div ng-app="">
<form>
Enter number: <input type="number" ng-model="number" onKeyPress="if(this.value.length==7) return false;" min="0">
</form>
<h1>You entered: {{number}}</h1>
</div>
If you use "onkeypress" event then you will not get any user limitations as such while developing ( unit test it). And if you have requirement that do not allow user to enter after particular limit, take a look of this code and try once.
Another option is to just add a listener for anything with the maxlength attribute and add the slice value to that. Assuming the user doesn't want to use a function inside every event related to the input. Here's a code snippet. Ignore the CSS and HTML code, the JavaScript is what matters.
// Reusable Function to Enforce MaxLength
function enforce_maxlength(event) {
var t = event.target;
if (t.hasAttribute('maxlength')) {
t.value = t.value.slice(0, t.getAttribute('maxlength'));
}
}
// Global Listener for anything with an maxlength attribute.
// I put the listener on the body, put it on whatever.
document.body.addEventListener('input', enforce_maxlength);
label { margin: 10px; font-size: 16px; display: block }
input { margin: 0 10px 10px; padding: 5px; font-size: 24px; width: 100px }
span { margin: 0 10px 10px; display: block; font-size: 12px; color: #666 }
<label for="test_input">Text Input</label>
<input id="test_input" type="text" maxlength="5"/>
<span>set to 5 maxlength</span>
<br>
<label for="test_input">Number Input</label>
<input id="test_input" type="number" min="0" max="99" maxlength="2"/>
<span>set to 2 maxlength, min 0 and max 99</span>
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 for simple implementation.
<input name="somename"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "6"
/>
Simple solution which will work on,
Input scroll events
Copy paste via keyboard
Copy paste via mouse
Input type etc cases
<input id="maxLengthCheck"
name="maxLengthCheck"
type="number"
step="1"
min="0"
oninput="this.value = this.value > 5 ? 5 : Math.abs(this.value)" />
See there is condition on this.value > 5, just update 5 with your max limit.
Explanation:
If our input number is more then our limit update input value this.value with proper number Math.abs(this.value)
Else just make it to your max limit which is again 5.
As stated by others, min/max is not the same as maxlength because people could still enter a float that would be larger than the maximum string length that you intended. To truly emulate the maxlength attribute, you can do something like this in a pinch (this is equivalent to maxlength="16"):
<input type="number" oninput="if(value.length>16)value=value.slice(0,16)">
I had this problem before and I solved it using a combination of html5 number type and jQuery.
<input maxlength="2" min="0" max="59" name="minutes" value="0" type="number"/>
script:
$("input[name='minutes']").on('keyup keypress blur change', function(e) {
//return false if not 0-9
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}else{
//limit length but allow backspace so that you can still delete the numbers.
if( $(this).val().length >= parseInt($(this).attr('maxlength')) && (e.which != 8 && e.which != 0)){
return false;
}
}
});
I don't know if the events are a bit overkill but it solved my problem.
JSfiddle
a simple way to set maxlength for number inputs is:
<input type="number" onkeypress="return this.value.length < 4;" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />
Maycow Moura's answer was a good start.
However, his solution means that when you enter the second digit all editing of the field stops. So you cannot change values or delete any characters.
The following code stops at 2, but allows editing to continue;
//MaxLength 2
onKeyDown="if(this.value.length==2) this.value = this.value.slice(0, - 1);"
HTML Input
<input class="minutesInput" type="number" min="10" max="120" value="" />
jQuery
$(".minutesInput").on('keyup keypress blur change', function(e) {
if($(this).val() > 120){
$(this).val('120');
return false;
}
});
Ugh. It's like someone gave up half way through implementing it and thought no one would notice.
For whatever reason, the answers above don't use the min and max attributes. This jQuery finishes it up:
$('input[type="number"]').on('input change keyup paste', function () {
if (this.min) this.value = Math.max(parseInt(this.min), parseInt(this.value) || 0);
if (this.max) this.value = Math.min(parseInt(this.max), parseInt(this.value) || 0);
});
It would probably also work as a named function "oninput" w/o jQuery if your one of those "jQuery-is-the-devil" types.
As with type="number", you specify a max instead of maxlength property, which is the maximum possible number possible. So with 4 digits, max should be 9999, 5 digits 99999 and so on.
Also if you want to make sure it is a positive number, you could set min="0", ensuring positive numbers.
<input type="number" maxlength="6" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);">
This worked for me with no issues
You can try this as well for numeric input with length restriction
<input type="tel" maxlength="3" />
<input type="number" onchange="this.value=Math.max(Math.min(this.value, 100), -100);" />
or if you want to be able enter nothing
<input type="number" onchange="this.value=this.value ? Math.max(Math.min(this.value,100),-100) : null" />
As I found out you cannot use any of onkeydown, onkeypress or onkeyup events for a complete solution including mobile browsers. By the way onkeypress is deprecated and not present anymore in chrome/opera for android (see: UI Events
W3C Working Draft, 04 August 2016).
I figured out a solution using the oninput event only.
You may have to do additional number checking as required such as negative/positive sign or decimal and thousand separators and the like but as a start the following should suffice:
function checkMaxLength(event) {
// Prepare to restore the previous value.
if (this.oldValue === undefined) {
this.oldValue = this.defaultValue;
}
if (this.value.length > this.maxLength) {
// Set back to the previous value.
this.value = oldVal;
}
else {
// Store the previous value.
this.oldValue = this.value;
// Make additional checks for +/- or ./, etc.
// Also consider to combine 'maxlength'
// with 'min' and 'max' to prevent wrong submits.
}
}
I would also recommend to combine maxlength with min and max to prevent wrong submits as stated above several times.
Since I was look to validate and only allow integers I took one the existing answers and improve it
The idea is to validate from 1 to 12, if the input is lower than 1 it will be set to 1, if the input is higher than 12 it will be set to 12. Decimal simbols are not allowed.
<input id="horaReserva" type="number" min="1" max="12" onkeypress="return isIntegerInput(event)" oninput="maxLengthCheck(this)">
function maxLengthCheck(object) {
if (object.value.trim() == "") {
}
else if (parseInt(object.value) > parseInt(object.max)) {
object.value = object.max ;
}
else if (parseInt(object.value) < parseInt(object.min)) {
object.value = object.min ;
}
}
function isIntegerInput (evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode (key);
var regex = /[0-9]/;
if ( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) {
theEvent.preventDefault();
}
}
}
More relevant attributes to use would be min and max.
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();
I use a simple solution for all inputs (with jQuery):
$(document).on('input', ':input[type="number"][maxlength]', function () {
if (this.value.length > this.maxLength) {
this.value = this.value.slice(0, this.maxLength);
}
});
The code select all input type="number" element where maxlength has defined.
If anyone is struggling with this in React the easiest solution that i found to this is using the onChange function like this:
const [amount, setAmount] = useState("");
return(
<input onChange={(e) => {
setAmount(e.target.value);
if (e.target.value.length > 4) {
setAmount(e.target.value.slice(0, 4));
}
}} value={amount}/>)
So what this basically does is it takes the value of the input and if the input value length is bigger than 4 it slices all the numbers after it so you only get the first 4 numbers (of course you can change the amount of numbers you can type by changing all 4's in the code). I hope this helps to anyone who is struggling with this issue. Also if you wanna learn what the slice method does you can check it out here
Non-optimal solutions
Rellying on min and max
As some people have pointed out, you can use max and min attributes to set the range of allowed values, but this won't prevent the user from typing longer text like maxlength attribute does.
keydown, keyup and other non-input event listeners
It is important to say that not all users work with a desktop keyboard so keydown or keyup events are not the best approch to accomplish this for all kind of input methods such as mobile keyboards
slice, substring and other String methods
This methods work well only if the user is typing at the end of the input, but if it is typing anywhere else, the character input won't be prevented. It will be added and the last character of the input will be removed instead
Solution for all situations
If you really want to prevent the character from being added to the input, when the desired length is reached (or any other condition is met), you can handle it using the beforeinput event listener which is supported for all major browsers: https://caniuse.com/?search=beforeinput.
It is called just before the input event listener which means the input value hasn't changed already, so you can store it an set to the input after.
const input = document.querySelector("input");
input.addEventListener("beforeinput", () => {
const valueBeforeInput = event.target.value;
event.target.addEventListener("input", () => {
if (event.target.value.length > 10) {
event.target.value = valueBeforeInput;
}
}, {once: true});
});
<input type=number />
If you want to support browsers before 2017 (2020 and 2021 for Edge and Firefox respectively) don't use the beforeinput event listener and use the code below instead.
const input = document.querySelector("input");
let valueBeforeInput = input.value;
input.addEventListener("input", () => {
if (event.target.value.length > 10) {
event.target.value = valueBeforeInput;
}
valueBeforeInput = event.target.value;
});
<input type=number />
This might help someone.
With a little of javascript you can search for all datetime-local inputs, search if the year the user is trying to input, greater that 100 years in the future:
$('input[type=datetime-local]').each(function( index ) {
$(this).change(function() {
var today = new Date();
var date = new Date(this.value);
var yearFuture = new Date();
yearFuture.setFullYear(yearFuture.getFullYear()+100);
if(date.getFullYear() > yearFuture.getFullYear()) {
this.value = today.getFullYear() + this.value.slice(4);
}
})
});