Change input to uppercase without css and without seeing the text changing - javascript

I have the following problem, I need to change the input on a textfield to uppercase, but I can't use css nor the usual way where you see the input changing to uppercase. The input has to appear in capitals from the beginning, I'm trying to find a way to do this but I need some help.
I've done this but it doesn't work, the idea was to change the noncapital input to capital using a KeyboardEvent:
<s:textfield id="textfield1" />
$("#textfield1").keypress(function(event) {
var isMinus = (event.keyCode >= 97) && (event.keyCode <= 122);
if(isMinus) {
var evento = document.createEvent("KeyboardEvent");
evento.initKeyboardEvent("onkeypress", true, true, window, event.keyCode - 32, event.location, "", event.repeat, event.locale);
event.currentTarget.dispatchEvent(evento);
}
});
Any tips? Thanks for reading!

You can try this:
$("#textfield1").keypress(function(event) {
var isMinus = (event.keyCode >= 97) && (event.keyCode <= 122);
if (isMinus) {
var letra = String.fromCharCode(event.keyCode-32);
this.value+= letra;
event.preventDefault();
event.stopPropagation();
}
});
Example: http://jsfiddle.net/kx23u3z1/
:)

You need to change it to id="textfield1"
Also, see my answer here for more on the topic: Allow text box only for letters using jQuery?
TL;DR - don't change the input unless the user has done something wrong, or you'll adjust the cursor position and frustrate the user.

Related

How to change value of input[type=number] on key press via Javascript?

I already have a series of events of keypress to trigger some sound, to run countdown clock and whatnot.
I also want to assign keycode to change the value of a couple of input[type=number], either subtract or add value by incremental of -1/+1 each key press. I have done some search but couldn't really give me the ultimate guide.
Here's what I have in the header.
function runScript(e){
if(e.keyCode == 32 && e.shiftKey){
gameclock();
}}
and on my html
<body onkeydown="runScript(event)">
...
<input id="whateverID1" type="number" value="00">
Let's say if I want to add #whateverID1 value by pressing = and subtract #whateverID1 value by pressing -, appreciate any guide to how can I achieve that. Thank you very much.
I have tried this but doesn't seem to work.
var CounterName = 0;
if(e.keyCode == 49 ) {
document.getElementById('whateverID1').value = ++CounterName;
}
if(e.keyCode == 50 ) {
document.getElementById('whateverID1').value = --CounterName;
}
For one, using onclick/onkeydown things in html is usually bad practice. Rather, give the element an id or class and add an eventListener from the JS instead.
Try this below, the jsfiddle is working and should let you do what you want:
document.getElementById("bodyId").addEventListener("keydown", function (event) {
var CounterName = 1;
var currentValue = parseInt(document.getElementById('whateverID1').value);
if(event.keyCode == 187) {
document.getElementById('whateverID1').value = currentValue + CounterName;
}
else if(event.keyCode == 189) {
document.getElementById('whateverID1').value = currentValue - CounterName;
}
});
http://jsfiddle.net/Maxmaxs5/7thqo0zs/7/
If this helps or you need anything else, let me know!

Capture keys typed on android virtual keyboard using javascript

I have a web page with a textarea, and I need to capture the keys typed by the user (so that I can substitute different unicode characters for the keys typed). My current code is as follows:
$("#myTextArea").bind('keypress', function(event) {
var keyInput = event.which;
// call other functions
});
This above code works on PCs, and iPhone/Safari. However, it fails when using Chrome on an android (samsung) tablet. For some reason when I type on the android virtual (soft) keyboard, the "keypress" event is not triggered. The android version is 5.0.2.
If I try using "keyUp" or "keyDown", it always returns 229 for all characters (except for return key, space, backspace, etc).
Even though the keyCode is always 229, the textarea displays the correct characters typed by the user. Which means the device knows which key was entered, but somehow I'm unable to get a handle on this event (and the key code) using javascript.
Here are the alternatives that I have tried so far, and their outcomes:
$("#mainTextArea").on("keydown keyup", function(event) {
// event.which and event.keyCode both return 229
$(document).on('keypress', function(event) {
// function is not triggered
$('#myTextArea').bind('input keypress', function(event) {
// comes inside function, but keyCode and which are undefined
Any help regarding this issue is appreciated..
Unfortunately it seems you cannot do much here.
Keypress event is deprecated, thus not fired.
229 on keyup and keydown indicates the keyboard buffer is busy. The reason - when you press a key - the input is still not guaranteed to be what the user pressed, because of auto suggest and other events that may follow immediately and invalidate the event.
Although in my opinion it would have been better to send the key first, then fire another event perhaps on auto suggest so you can act upon it separately...
The only thing that I currently know of is to attach to both - keydown and keyup, store the value on keydown, get the value on keyup and find the delta, which is what user pressed. Unfortunately this will not work for non-input controls (e.g. - the body or something like that).
Maybe not what you want to hear as answer but still.
I came across this discussion while doing research for a project I was working on. I had to create input masks for a mobile app, and Pavel Donchev's answer got me thinking about what could work to capture keys in Android. In my specific project, keydown and keyup would not be enough because keyup event is only triggered after a key is released, so it would imply in a late validation, so I did some more research (and lots of trial and error) with input events and got it working.
var input = document.getElementById('credit-card-mask'),
oldValue,
newValue,
difference = function(value1, value2) {
var output = [];
for(i = 0; i < value2.length; i++) {
if(value1[i] !== value2[i]) {
output.push(value2[i]);
}
}
return output.join("");
},
keyDownHandler = function(e) {
oldValue = input.value;
document.getElementById("onkeydown-result").innerHTML = input.value;
},
inputHandler = function(e) {
newValue = input.value;
document.getElementById("oninput-result").innerHTML = input.value;
document.getElementById("typedvalue-result").innerHTML = difference(oldValue, newValue);
}
;
input.addEventListener('keydown', keyDownHandler);
input.addEventListener('input', inputHandler);
<input type="text" id="credit-card-mask" />
<div id="result">
<h4>on keydown value</h4>
<div id="onkeydown-result"></div>
<h4>on input value</h4>
<div id="oninput-result"></div>
<h4>typed value</h4>
<div id="typedvalue-result"></div>
</div>
The oninput event is triggered right after the keydown event, which is the perfect timing for my validations.
I compiled the whole thing in an article. If you're curious, you can read about it here.
I ran into the same issue. Several explanations are out there but anyhow it seems strange that no solution is offered.
For the moment I solved it by capturing the oninput event.
"This event is similar to the onchange event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed"
This event support inserted text too, from pasting text or from corrections & suggestions.
it doesn't give me the perfect solution cause I can only manipulate the text AFTER it has been entered, but for the moment it is the best I have.
If anyone has a better solution I will be glad to hear about it.
just check your input characters keyCode, if it is 0 or 229 then here is the function getKeyCode() which uses charCodeAt of JS to return the KeyCode which takes input string a parameter and returns keycode of last character.
<script>
var getKeyCode = function (str) {
return str.charCodeAt(str.length);
}
$('#myTextfield').on('keyup',function(e){
//for android chrome keycode fix
if (navigator.userAgent.match(/Android/i)) {
var inputValue = this.value;
var charKeyCode = e.keyCode || e.which;
if (charKeyCode == 0 || charKeyCode == 229) {
charKeyCode = getKeyCode(inputValue);
alert(charKeyCode+' key Pressed');
}else{
alert(charKeyCode+' key Pressed');
}
}
});
</script>
There is a textInput event that gives you the entered character
const inputField = document.getElementById('wanted-input-field');
inputField.addEventListener('textInput', function(e) {
// e.data will be the 1:1 input you done
const char = e.data; // In our example = "a"
// If you want the keyCode..
const keyCode = char.charCodeAt(0); // a = 97
// Stop processing if "a" is pressed
if (keyCode === 97) {
e.preventDefault();
return false;
}
return true;
});
I recently implemented a "mentions" feature in the latest version of our Astro AI assisted Email app. Basically you type "#" in our compose web view and you get a list of autocomplete suggestions. We, like most other people, had problems trying to solve this in the Javascript. What eventually worked was a native solution. If you #Override the WebView's onCreateInputConnection() method, you can wrap the super.onCreateInputConnection() result (which is just an InputConnection interface) with a custom class. Then in your wrapper implementation, you can trap input via commitText() or setComposingText() or maybe some other method specific to what you are looking for...like deletes. I don't know if you would get any callbacks on control characters like up and down arrows but maybe this can be a place to start to solve your specific problem.
You can approach it from a different perspective by using the selectionstart property:
Returns / Sets the beginning index of the selected text. When nothing
is selected, this returns the position of the text input cursor
(caret) inside of the <input> element [also applies to <textarea>].
Source: MDN
I do something like this in my own app and it has worked reliably...
document.querySelector('textarea').addEventListener('input', (e) => {
const elInput = e.target;
// Get start of selection (caret offset when typing)
const nSelStart = elInput.selectionStart;
// Get last typed character (modify for your own needs)
const sLastTyped = elInput.value.substr(nSelStart-1, 1);
console.log('Last typed character:', sLastTyped);
});
textarea {
width: 99%;
height: 4rem;
}
<textarea placeholder="Enter something using Android soft keyboard"></textarea>
Codepen: https://codepen.io/thdoan/full/dymPwVY
I FIGURED IT OUT!
Here's a 100% working solution that works EVERYWHERE with EVERY feature, including even emoji suggestions on iOS and any pasted content. I'm using substring comparison to find actual stuff that changed from onInput to onInput.
Points from which to which text is deleted and from which to which it's inserted are pointed out.
Rating and selecting as an answer is appreciated.
var x = document.getElementById("area"),
text = x.value,
event_count = 0
function find_Entered_And_Removed_Substrings(
previous_string, current_string, pos
) {
let
right_pos = pos,
right_boundary_of_removed =
previous_string.length -
(
current_string.length -
pos
),
left_max_pos = Math.min(
pos,
right_boundary_of_removed
),
left_pos = left_max_pos
for (
let x = 0; x < left_max_pos; x++
) {
if (
previous_string[x] !==
current_string[x]
) {
left_pos = x
break
}
}
return {
left: left_pos,
right: pos,
removed_left: left_pos,
removed_right: right_boundary_of_removed
}
}
x.oninput =
(e) => {
// debugger;
let
cur_text = x.value,
positions =
find_Entered_And_Removed_Substrings(
text, cur_text, Math.max(
x.selectionStart, x.selectionEnd
)
)
console.log(positions)
let
entered =
cur_text.substring(
positions.left, positions.right
),
removed =
text.substring(
positions.removed_left, positions.removed_right
)
if (
entered.length >
0 ||
removed.length >
0
) {
document.getElementById("entered")
.innerHTML +=
entered
document.getElementById("removed")
.innerHTML +=
removed
document.getElementById("events")
.innerHTML =
event_count++
}
text = cur_text
}
<textarea id="area"></textarea>
<br/>
<pre id="entered"></pre>
<br/>
<div id="events"></div>
<pre id="removed"></pre>

How to limit typing number in text input

I have an text input for pagination page changing. I need to limit typing of page numbers to some number f.e. 15 (max pages number). So i'm trying with this code below but always when number is higher than 15 value is changing to 15 and actual typing number.
actual.on('keypress', function() {
console.log('test');
var t = $(this);
if (t.val() < 1) t.val('1');
if (t.val() > 15) t.val('15');
});
Fiddle: http://jsfiddle.net/v6fhobr7/
Can anybody help?
Try changing it from 'keypress' to 'keyup' ... there's a slight flicker, but it works.
Use a number field.
<input type="number" min="1" max="15" step="1">
#rfornal's solution works okay, but it's hard to type single digit value unless you're really fast:
http://jsfiddle.net/v6fhobr7/7/
So it's better to set a slight timeout before changing the value:
var actual = $('.actual');
var tm;
actual.on('keyup', function () {
var t = $(this);
if (tm) clearTimeout(tm);
tm = setTimeout(function() {
if (t.val() < 1) t.val('1');
if (t.val() > 15) t.val('15');
}, 250);
});
JSFiddle demo: http://jsfiddle.net/v6fhobr7/10/
In jQuery 2.x, you can use actual.on('input'), which does what you want without the flicker.
Note that this will prevent the user from clearing out the input entirely; if you want to allow this then you might want to handle the case where t.val() == '' explicitly.
actual.on('input', function(e) {
var t = $(this);
if (t.val() == '') return;
if (t.val() < 1) t.val('1');
if (t.val() > 15) t.val('15');
});
http://jsfiddle.net/v6fhobr7/12/
Edit:
Note that this solution doesn't restrict input to only numeric characters (you can still type letters and symbols). If you want to prevent that, use this solution in addition to my answer above.
Or, if you don't care about IE 9 or mobile browsers, Mathletics's answer is the best.

Have an irremovable question mark at the end of html input

I've looked around for ages trying to figure out this, hope you can help me.
Basically I have a feature on my site where the user can post a question. Essentially I want a permanent question mark at the end of what they're typing. The question mark is already added in the back end so this is strictly a visual problem.
The question mark moves up when they type.
I can't attach a photo but you can imaging :
The user typing here and after the type line there's a trailing question mark (type line-->)|?
Thanks in advance!!
You could do this :
$('#a').keyup(function(){
var v = this.value.replace(/\?/g, '') + '?';
if (this.value != v) this.value = v;
});
Demonstration
But users don't really like when the content of the input changes of its own. I'd avoid this if possible.
This second version puts a space before the ? :
$('#a').keyup(function(){
var v = this.value.replace(/ ?\?/g, '') + ' ?';
if (this.value != v) this.value = v;
});
Demonstration
Use a little javascript.
Attach an event onto the onkeyup event of the tickbox, and whenever it fires, check to see if the contents end with a question mark. If it doesn't, then add it!
Personally though, it would annoy me, as a user-I'd prefer to only see the question mark once I'be submitted.
I would perhaps instead recommend that you do a check on the server to see if the question contains a question mark (or multiple) at the end, then replace/add the single question mark.
As stated already, it's not really friendly to force a certain input - do the proper checks yourself and take the burden off the user.
If the goal is simply visual reinforcement, then it might be easiest to put a text or graphical question mark outside the text input, possibly in an interesting color, like bold green.
You don't really want to be trying to manipulate the input as the user is typing; you will likely always run into edge cases where the content gets mangled. If it's purely for presentational purposes, just add a ? character just after the input; if you surround it with something like a span, you can target it with CSS to adjust its size or font weight to make it more obvious:
.jumbo
{
font-size: 2em;
}
<input /><span class="jumbo">?</span>
An alternate solution (but overkill if you aren't already using it) is to use an icon font like FontAwesome and add, say, the question-mark icon: http://fortawesome.github.io/Font-Awesome/icon/question/
<input /><i class="icon-question icon-large"></i>
you can put the editable text inside a contenteditable span followed by another span that has the non editable question mark.
http://jsfiddle.net/Paawn/1/
<div class="box">
<span contenteditable="true">This is content i can edit</span>
<span class="question-mark">?</span>
</div>
Here's a pretty decent solution built off of ideas above and elsewhere on stack overflow. Using jQuery
Just add the following snippet and then add the class questionableInput to your input
<input id="yourInput" type="text" name="theInput" class="questionableInput"/>
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
}
}
$.fn.setCursorPosition = function(pos) {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
input.selectionStart = pos;
input.selectionEnd = pos;
}
}
$(".questionableInput").keyup(function(e) {
if (e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40 || e.keyCode == 13
|| e.keyCode == 8 || e.keyCode == 17 || e.keyCode == 16 || e.keyCode == 36 || e.keyCode == 63
|| e.keyCode == 35 || e.ctrlKey) {
return;
}
var positionBeforeMessingWithIt = $(this).getCursorPosition();
if (this.value.slice(-1)!='?') this.value += '?';
if (this.value.slice(-2)=="??") this.value = this.value.substring(0, this.value.length - 1);
$(this).setCursorPosition(positionBeforeMessingWithIt);
});
})(jQuery);
http://jsfiddle.net/YpEgN/2/

JavaScript to accept only numbers between 0 to 255 range

My Requirement is to validate the ip ranges, I need to create a JavaScript function to accept only numeric and it must allow only between the range 0 to 255. If anything is entered beyond that it must alert a message.
I am currently using this below function
<script language="JavaScript">
function allownums(a)
{
if(a <48 ||a > 57)
alert("invalid")
else
alert("vaild")
}
</script>
<input type='text' id='numonly' onkeypress='allownums(event.keycode)'>
I am new to JavaScript, Need some experts suggestion to fix my requirement. Please suggest me
Thanks
Sudhir
Currently you have the test
(a < 48) || (a > 57)
for invalid values. So I would change those:
(a < 0 ) || (a > 255)
You may also need to consider what you'll do with non-integral input like 2.3 - either round it or treat it as invalid.
At present, as Kelvin Mackay points out, you are performing the validation on the keypress event rather than the input value, so change the onkeypress to allownums(this.value).
I would advise changing the alert to a warning in a div, and using the validation to enable/disable a submit button, as popups are quite annoying in just about every circumstance.
To clear the input when an invalid entry is made (as requested in a comment) would make it rather annoying for the user; as soon as a key is pressed to add a digit and make the input invalid, the whole input is cleared. The code, however, would be:
if(!validnum(this.value))
this.value="";
in the input tag, thus:
<input type='text' id='numonly'
onkeyup='if(!validnum(this.value)) this.value="";'>
with the function changed to:
function validnum(a) {
if(a < 0 || a > 255)
return false;
else
return true;
}
or more succinctly:
function validnum(a) {
return ((a >= 0) && (a <= 255));
}
Edit: To alert and clear the box, if you must:
function validOrPunchTheUser(inputElement) {
if(!validnum(inputElement.value)) {
window.alert('badness'); // punch the user
inputElement.value = ""; // take away their things
}
}
<input type='text' id='numonly'
onkeyup='validOrPunchTheUser(this)'>
However, reading other answers, apparently you are looking to validate an octet (e.g. in an IP address). If so, please state that in the question, as it passed me by today. For an octet:
function validateIPKeyPress(event) {
var key = event.keyCode;
var currentvalue = event.target.value;
if(key < 96 || key > 105)
{
event.preventDefault();
window.alert('pain');
return false;
}
else if(currentvalue.length > 2 ||
(currentvalue.length == 2 &&
key > 101)) {
window.alert('of death');
event.preventDefault();
event.target.value = event.target.value.substring(0,2);
}
else
return true;
}
With the input tag:
<input type='text' id='octet'
onkeydown='validateIPKeyPress(event)'>
Except please don't use alerts. If you take out the alert lines, it will silently prevent invalid inputs. Note the change to use onkeydown now, so that we can catch invalid key presses and prevent the value changing at all. If you must clear the input, then do if(!validateIPKeyPress(event)) this.value = "";.
I would rather go instantly for validation of whole ip address. Allowing input both numbers and dots, parsing them thru REGEX pattern.
Pattern usage example you could fetch here:
http://www.darian-brown.com/validate-ip-addresses-javascript-and-php-example/
The code itself would look something like:
<input type='text' id='numonly' value="" onkeypress='allowIp(event)' onkeyup='javascript:checkIp()'>
function allowIp(e){
if((e.keyCode < 48 || e.keyCode > 57) && e.keyCode != 46) // both nubmer range and period allowed, otherwise prevent.
{
e.preventDefault();
}
}
function checkIp()
{
var ip = $("#numonly").val();
/* The regular expression pattern */
var pattern = new RegExp("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
/* use javascript's test() function to execute the regular expression and then store the result - which is either true or false */
var bValidIP = pattern.test(ip);
if(bValidIP){
// IP has ok pattern
$("#numonly").css("background", "green");
}
else {
$("#numonly").css("background", "red");
}
}
You could check it here on fiddle
http://jsfiddle.net/Indias/P3Uwg/
Single Integer
You can use the following solution to check if the user input for a single integer is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(/^\d+$/.test(input) && input > -1 && input < 256);
});
<input id="example" type="text" placeholder="Enter single integer" />
IP Address
Alternatively, you can use the code below to verify that each section of an IP address is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(input === new Uint8ClampedArray(input.split('.')).join('.'));
});
<input id="example" type="text" placeholder="Enter IP address" />
You need to validate the current value of the input, rather than the last key that was pressed:
<input type='text' id='numonly' onkeypress='allownums(this.value)'>
Your function then just needs to be modified to: if(a < 0 || a > 255)
A function like this should do it:
function allownums(value){
var num = parseInt(value,10);
if(num <0 || num>255)
alert('invalid')
}
Then have your html look like:
<input type='text' id='numonly' onblur='allownums(this.value)'>
Live example: http://jsfiddle.net/USL3E/
Update
I've set up a fiddle that does some basic IP-formatting and checks weather or not all input is in range (0 - 255) etc... feel free to use it, improve it, study it... I've also updated the code snippet here to match the fiddle
There are several things you're not taking into account. First and foremost is that not all browsers have a keycode property set on the event objects. You're better off passing the entire event object to the function, and deal with X-browser issues there. Secondly, you're checking key after key, but at no point are you checking the actual value that your input field is getting. There are a few more things, like the use of the onkeypress html attribute (which I don't really like to see used), and the undefined return value, but that would take us a little too far... here's what I suggest - HTML:
<input type='text' id='numonly' onkeypress='allowNums(event)'>
JS:
function allowNums(e)
{
var key = e.keycode || e.which;//X-browser
var allow = '.0123456789';//string the allowed chars:
var matches,element = e.target || e.srcElement;
if (String.fromCharCode(key).length === 0)
{
return e;
}
if (allow.indexOf(String.fromCharCode(key)) === 0)
{//dot
element.value = element.value.replace(/[0-9]+$/,function(group)
{
return ('000' + group).substr(-3);
});
return e;
}
if (allow.indexOf(String.fromCharCode(key)) > -1)
{
matches = (element.value.replace(/\./g) + String.fromCharCode(key)).match(/[0-9]{1,3}/g);
if (+(matches[matches.length -1]) <= 255)
{
element.value = matches.join('.');
}
}
e.returnValue = false;
e.cancelBubble = true;
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}​
Now this code still needs a lot of work, this is just to get you going, and hopefully encourage you to look into the event object, how JS event handlers work and all the rest. BTW, since you're new to JS, this site is worth a bookmark
function fun_key()
{
var key=event.keyCode;
if(key>=48 && key<=57)
{
return true;
}
else
{
return false;
alert("please enter only number");
}
}
and you can call this function on keypress event like:
<asp:textbox id="txtphonenumber" runat="server" onkeypress="return fun_key()"> </asp"textbox>
I've seen many answers that have overlooked two important factors that may fail to validate range number on keypress:
When the value in input textbox is NOT SELECTED, the real outcome should be (input.value * 10) + parseInt(e.key) and not simply input.value + parseInt(e.key). It should be * 10 because you add one more digit at the back during keypress, e.g. 10 becomes 109.
When the value in input textbox IS SELECTED, you can simply check if Number.isInteger(parseInt(e.key)) because when 255 is selected, pressing 9 will not turn into 2559 but 9 instead.
So first of all, write a simple function that check if the input value is selected by the user:
function isTextSelected (input) {
if (!input instanceof HTMLInputElement) {
throw new Error("Invalid argument type: 'input'. Object type must be HTMLInputElement.");
};
return document.getSelection().toString() != "" && input === document.activeElement;
}
Next, this will be your on keypress event handler that takes into consideration of the above two factors:
$("input[type='number']").on("keypress", function (e) {
if (!Number.isInteger(parseInt(e.key)) || (($(this).val() * 10) + parseInt(e.key) > 255
&& !isTextSelected($(this)[0]))) {
e.preventDefault();
};
});
Take note of this condition within another brackets, it is one whole condition by itself:
(($(this).val() * 10) + parseInt(e.key) > 255 && !isTextSelected($(this)[0]))
For the < 0 condition, you don't even need it here because the negative sign (-) will be automatically prevented as the sign itself is not an integer.
KNOWN ISSUE: The above solution, however, does not solve the situation when the user move the cursor to the start position of 29 and press 1, which will become 129. This is because 29 * 10 = 290, which already exceed 255, preventing user from entering 129, which is valid. The start position is particularly hard to track when the input type="number". But it should be enough to resolve the normal way of input for an integer range field. Any other better solutions are welcome.

Categories