Don't allow to reach higher than 9999 on an input? [duplicate] - javascript

This question already has answers here:
How to limit typing number in text input
(4 answers)
Closed 4 years ago.
$(document).on('keyup keydown',function(key){
if(key.which >= 48 && key.which <= 57 && $('#sell').val() >= 9999 ) {
return false;
}
else {
if(key.which >= 48 && key.which <= 57 && $('#sell').val() <= 9999 ) {
return true;
}
}
});
Basically what I want to do is prevent someone from reaching higher than 9999 on an input.
But the problem is that if they type "55555" it would go through.
They couldn't type any higher than that and could delete it, but I don't want them to get higher than 9999.
Does anyone have a solution?
EDIT:
I need to somehow also prevent the input from working if it detects a higher number.

Try this:
var lastVal;
$("#sell").on('keydown', function(e){
if(e.which === 8){ // allow backspace
return;
} else if((e.which < 48 || e.which > 57) && (e.which < 96 || e.which > 105) ) { //only allow numbers & num pad numbers
return false;
}
if(e.target.value <= 9999) lastVal = e.target.value; //prevent key holding
});
$("#sell").on('keyup', function(e){
if(e.target.value > 9999){
e.target.value = lastVal;
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id=sell />

You could try something like this:
let sell = $('#sell');
let lastVal = 0;
sell.on('keyup keydown', function(key) {
let cc = key.which;
return (cc <= 57 && cc !== 32);
});
sell.on('input', function(evt) {
const newVal = sell.val();
if (newVal < 0 || newVal > 9999) {
sell.val(lastVal);
}
else {
lastVal = newVal;
}
});
Note that this only captures key events on the input itself, not the whole document. While this limits the user to typing digits (character below 48 (except space) are allowed because those are things like arrow keys and backspace), more work would be needed if you wanted to allow the user to perform actions like copy and paste.
The reason for not testing the val() of the input in the key event handler is a matter of timing: The key down event doesn't change the value of the input field, and the key up event comes after the value has been updated and it's too late to prevent the value change.
What this code does instead is let the value momentarily go out of range, but immediately reset it to the last valid value when that happens.
Plunker here: http://plnkr.co/edit/xsVQG1EzsDLMt8POCJUX?p=preview

Make the max length equal to 4 in HTML and use JS to force integer type, put max on input to prevent higher than 9999... Or do it manually for all of it . Up to you
With JS... on keydown: Strip non integers
if($("#inputID").val().length > 4){ KILL EXTRA LETTERS }
Once done.
If ($("#inputID").val() > 9999){ $("#inputID").val(9999); }
Remember, if this is for a form to validate the answer on the server side so the client can't override HTML and JS checks.

Related

Not allow Korean character(Hangul) for input text

I want to allow typing Latin Characters but I don't want user can type Korean Hangul characters.
Please help me answer. Thank you in advance.
Based on this article,
https://en.wikipedia.org/wiki/Korean_language_and_computers
You would want to do something like this (untested):
$(document).on('keypress', 'input', function (e) {
var key = event.which || event.keyCode;
// Hangul Syllables
if (key >= 0xAC00 && key <= 0xD7A3) {
e.preventDefault();
}
// Hangul Jamo
if (key >= 0x1100 && key <= 0x11FF) {
e.preventDefault();
}
// Hangul Compatibility Jamo
if (key >= 0x3130 && key <= 0x318F) {
e.preventDefault();
}
// Hangul Jamo Extended-A
if (key >= 0xA960 && key <= 0xA97F) {
e.preventDefault();
}
// Hangul Jamo Extended-B
if (key >= 0xD7B0 && key <= 0xD7FF) {
e.preventDefault();
}
});
However, this would not stop anyone from copying/pasting Hangul characters into the input field, you would need to find something separate for that.
A more simplified way is to use form validation (this is a more simplified approach):
<input type="text" pattern="[^가-힣]+">
What you should do is instead be testing for the characters on the server side and returning a form error.

How to use Javascript to filter and ignore keypresses on an input field?

I need to stop accepting input (keystrokes) on an HTML form input field when the length limit has been reached. In straight-up HTML I can do this with maxlength="3" or whatever the length is, but I would like to handle it through Javascript if possible so I can do it together with the next requirement.
I also need to filter the input so that if a field is numeric only numbers can be typed, and if there's a mask or regex any inputs conform to the mask/regex.
Is there a "standard" way to do this in, Javascript, particularly in Dojo 1.9? (I know everybody uses JQuery but we use Dojo because.)
For dojo, if you need any sort of validation, I would use the ValidationTextBox, which takes "maxLength" as a property AND allows for all sorts of nifty validation schemes. The reference for ValidationTextBox is here:
http://dojotoolkit.org/reference-guide/1.9/dijit/form/ValidationTextBox.html
I used pure Javascript because I am not familiar with Dojo, but these event listeners can probably be cleaned up with Dojo.
var input = document.getElementsByTagName('input')[0],
error = document.getElementById('error');
input.addEventListener('keypress', function(e) {
if(e.which < 48 || e.which > 57) {
e.preventDefault();
error.innerHTML = 'Must be a digit';
} else if(e.target.value.length >= 3) {
e.preventDefault();
error.innerHTML = 'Cannot be more than 3 digits';
} else {
error.innerHTML = '';
}
});
We listen to a keypress and then, to make sure it is a digit, we seek that the key pressed was between 48-57 (0-9). If not, then we prevent the key press and show an error. Then we check the input's current length. If it is too long, then prevent the key press and show an error. Otherwise, it worked and we allow the event and clear the error.
You maybe looking for this:
<input id="text" type="text"/>
$('#text').on('keypress',function(e){
var numero = this.value.length;
console.log(this.value.length);
if (e.which != 8 && e.which < 48 || e.which > 57)
{
return false
}
else if (numero === 3 && e.which != 8){
return false //alert user here
}else{
return true // allow backspace only (8)
}
}
);
DEMO

Which is the proper way of filtering numeric values for a text field?

I'm working on a textfield working with the kind of validation that wouldn't let you enter other than numeric values. As so, my initial code looked quite simple and similar to this:
$(textField).onKeyPress(function(e) {
if (e.which < 48 && e.which > 57)
e.preventDefault();
});
This is fairly strightforward, but turns that (in the latest version of all browsers) Firefox will make this also prevent movement with the arrow keys and delete/backspace keys, whereas the other browsers would not.
Looking around I found that I would need to also check for these keys, and check for different properties exposed in the e event reference.
My final code looks something like this:
$(textField).onKeyPress(function(e) {
var code = e.which || e.keyCode;
if (code > 31 // is not a control key
&& (code < 37 || code > 40) // is not an arrow key
&& (code < 48 || code > 57) // is not numeric
&& (code != 46) // is not the delete key
)
e.preventDefault();
});
However, this feels to be too much to solve a fairly simple problem as just preventing non-numeric.
What am I doing wrong? Which is the best practice in terms of this kind of validation?
We'll respond to both keypresses, and the blur event. When somebody press a key, we check to see if the key entered is a number. If it is, we permit it. Otherwise, we prevent it.
If the field is blurred, we remove any non-numerical values, and all those values that follow. This will prevent the user from pasting in non-numerical strings:
$("#textfield").on("keypress blur", function(e){
if ( e.type === "keypress" )
return !!String.fromCharCode(e.which).match(/^\d$/);
this.value = this.value.replace(/[^\d].+/, "");
});
Demo: http://jsfiddle.net/jonathansampson/S7VhV/5/
Working demo http://jsfiddle.net/Pb2eR/23/ Updated Copy/Paste demo: http://jsfiddle.net/Pb2eR/47/ (In this demo wit you copy paste string with characters it won't allow else it will allow number to be copy pasted: tested in safari)
Demo for arrow key to work http://jsfiddle.net/gpAUf/
This will help you.
Note: in this version even if you copy paste it will set it to empty input box, tested in safari lion osx :)
Good Link: [1] How to allow only numeric (0-9) in HTML inputbox using jQuery?
code
$(".hulk").keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
​
html
<input type="text" class="hulk" value="" />
​
Update for copy paste stuff
$(".hulk").keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
$(".hulk").bind('input propertychange', function() {
this.value = this.value.replace(/[^0-9\.]/g,'');
});​
code from another demo
$(".hulk").bind('input propertychange', function(event) {
if( !(event.keyCode == 8 // backspace
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105)) // number on keypad
) {
event.preventDefault(); // Prevent character input
}
this.value = this.value.replace(/[^0-9\.]/g,'');
});
​
this will allow both int.
it also removes text if user copy and paste with mouse.
$(document).ready(function () {
$('#textfield').bind('keyup blur', function (e) {
if (e.type == 'keyup') {
if (parseInt($(this).val()) != $(this).val()) {
$(this).val($(this).val().slice(0, $(this).val().length - 1));
}
} else if (e.type == 'blur') {
$(this).val('');
}
});
});

CLEditor - Lose focus if maxlength is reached

I'm trying to recreate a maxlength - function for CLEditor. The objective is:
If a text is entered into a textbox and its longer than the set maxlength, the textbox should lose its focus so that it's not possible, to write any further letters.
What I've achieved so far is that the CLEditor recognizes when the text gets longer than my maxlength.
For losing the focus I've tried a simple return (i.e. return; return false;) and some .blur()-methods (i.e. $(frameDesc).blur(); and cledDesc.$area.blur();).
But those are not working. I'm still able to fill in text even maxlength is reached.
Please have a look at the code:
$("#profileForm_description").cleditor({width: 430, height: 125});
var cledDesc = $("#profileForm_description").cleditor()[0];
var frameDesc = cledDesc.$frame[0].contentWindow.document;
$(frameDesc).bind('keypress change', function(){
var text = textWithoutHTML(cledDesc.$area.val());
if(text.length >= 650){
console.log("Longer than MaxLength");
//lose focus
}else{
//Do something
}
});
Any help and hints would be appreciated :)
Solved this one. That was pretty tricky. The solution (for me) is:
Using the keydown instead of the keypress - event.
So if I'm trying to put in some text in my textbox and maxlength is reached, I'm not able to go on writing. But to be able to delete some text, I need to except the Backspace-key from being rejected too. So I've put in a check, if the pressed key is the backspace-key.
This is what the code looks like now:
$("#profileForm_description").cleditor({width: 430, height: 125});
var cledDesc = $("#profileForm_description").cleditor()[0];
var frameDesc = cledDesc.$frame[0].contentWindow.document;
$(frameDesc).bind('keydown change', function(event){
var text = textWithoutHTML(cledDesc.$area.val());
if(text.length >= 650 && event.which != 8){
console.log("Longer than MaxLength");
//lose focus / stop writing
return false;
}else{
//Do something
}
});
I've added some code to make it work.
I catch even the "canc" key (and others)
Before checking the length of the text I update the textarea, it looks like CLEditor has an internal cache and I had a strange behaviour after deleting and reentering text.
This is working perfectly for me:
var cledDesc = $("#oodsummary").cleditor()[0];
var frameDesc = cledDesc.$frame[0].contentWindow.document;
var limit = 10;
$(frameDesc).bind('keydown', function(event){
cledDesc.updateTextArea();
var text = cledDesc.$area.val();
if(text.length >= limit &&
event.which != 8 && // back
event.which != 46 && // canc
event.which != 37 && // left
event.which != 38 && // up
event.which != 39 && // right
event.which != 16 && // shift
event.which != 20 && // caps lock
event.which != 91 && // os special
event.which != 18 // alt
) {
alert("Il testo inserito risulta essere troppo lungo.");
cledDesc.$area.val(text.substr(0, limit)).blur();
return false;
}else{
cledDesc.updateTextArea();
return true;
}
});

Allow text box only for letters using jQuery?

I want to make a text box allow only letters (a-z) using jQuery.
Any examples?
<input name="lorem" onkeyup="this.value=this.value.replace(/[^a-z]/g,'');">
And can be the same to onblur for evil user who like to paste instead of typing ;)
[+] Pretty jQuery code:
<input name="lorem" class="alphaonly">
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^a-z]/g,'') ); }
);
</script>
Accepted answer
The accepted answer may be short, but it is seriously flawed (see this fiddle):
The cursor moves to the end, no matter what key is pressed.
Non-letters are displayed momentarily, then disappear.
It is problematic on Chrome for Android (see my comment).
A better way
The following creates an array of key codes (a whitelist). If the key pressed is not in the array, then the input is ignored (see this fiddle):
$(".alpha-only").on("keydown", function(event){
// Allow controls such as backspace, tab etc.
var arr = [8,9,16,17,20,35,36,37,38,39,40,45,46];
// Allow letters
for(var i = 65; i <= 90; i++){
arr.push(i);
}
// Prevent default if not in array
if(jQuery.inArray(event.which, arr) === -1){
event.preventDefault();
}
});
Note that this allows upper-case and lower-case letters.
I have included key codes such as backspace, delete and arrow keys. You can create your own whitelist array from this list of key codes to suit your needs.
Modify on paste only
Of course, the user can still paste non-letters (such as via CTRL+V or right-click), so we still need to monitor all changes with .on("input"... but replace() only where necessary:
$(".alpha-only").on("input", function(){
var regexp = /[^a-zA-Z]/g;
if($(this).val().match(regexp)){
$(this).val( $(this).val().replace(regexp,'') );
}
});
This means we still have the undesired effect of the cursor jumping to the end, but only when the user pastes non-letters.
Avoiding autocorrect
Certain touchscreen keyboards will do everything in their power to autocorrect the user wherever it deems necessary. Surprisingly, this may even include inputs where autocomplete and autocorrect and even spellcheck are off.
To get around this, I would recommend using type="url", since URLs can accept upper and lower case letters but won't be auto-corrected. Then, to get around the browser trying to validate the URL, you must use novalidate in your form tag.
To allow only lower case alphabets, call preventDefault on the event object if the key code is not in the range 'a'..'z'. Check between 65..90 or 'A'..'Z' too if upper case should be allowed.
Or, alternatively use one of the many input mask plugins out there.
See example.
​$(<selector>).keypress(function(e) {
if(e.which < 97 /* a */ || e.which > 122 /* z */) {
e.preventDefault();
}
});​​​​​
// allow only Alphabets A-Z a-z _ and space
$('.alphaonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^A-Za-z_\s]/,'') ); } // (/[^a-z]/g,''
);
// allow only Number 0 to 9
$('.numberonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^0-9]/,'') ); } // (/[^a-z]/g,''
);
Demonstrated below to allow only letters [a-z] using Jquery:
$(function() {
$('#txtFirstName').keydown(function(e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input id="txtFirstName" value="">
Solution described by #dev-null-dweller is working absolutely.
However, As of jQuery 3.0, .bind() method has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.
Check deprecated methods list for jQuery 3.0 here: http://api.jquery.com/category/deprecated/deprecated-3.0/
So the solution is to use .on() method instead .bind().
If you need to bind existing elements then the code will be :
$('.alphaonly').on('keyup blur', function(){
var node = $(this);
node.val( node.val().replace(/[^a-z]/g,'') );
});
If you need to bind to dynamic elements the code will be :
$(document).on('keyup blur', '.alphaonly', function(){
var node = $(this);
node.val(node.val().replace(/[^a-z]/g,'') );
});
You need to bind the event to document or some other element that already exist from the document load.
Hope this is helpful for new version of jQuery.
$("#test").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
$("#test1").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
$("#test3").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32)||(inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For letters:<input type="text" id="test"> <br>
<br>
For Numbers: <input type="text" id="test1">
<br>
<br>
For Alphanumeric: <input type="text" id="test3">
Thanks to the first answer.. made this..
<input name="lorem" class="alpha-only">
<script type="text/javascript">
$(function()
{
$('.alpha-only').bind('keyup input',function()
{
if (this.value.match(/[^a-zA-Z áéíóúÁÉÍÓÚüÜ]/g))
{
this.value = this.value.replace(/[^a-zA-Z áéíóúÁÉÍÓÚüÜ]/g, '');
}
});
});
</script>
This has some improvements like letters with accents, and changing "blur" for "input" corrects the Non-letters displayed momentarily, also when you select text with the mouse and dragging is corrected..
JQuery function to allow only small and Capital Letters:
Text Field:
<input id="a" type="text" />
JQuery Function:
$('#a').keydown(function (e) {
if (e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
Supports backspace:
new RegExp("^[a-zA-Z \b]*$");
This option will not check mobile. So you can use a jQuery Mask Plugin and use following code:
jQuery('.alpha-field, input[name=fname]').mask('Z',{translation: {'Z': {pattern: /[a-zA-Z ]/, recursive: true}}});
$("#txtName").keypress(function (e) {
var key = e.keyCode;
if ((key >= 48 && key <= 57) || (key >= 33 && key <= 47) || (key >= 58 && key <= 64) || (key >= 91 && key <= 96) || (key >= 123 && key <= 127)) {
e.preventDefault();
}
var text = $(this).val();
$(this).val(text.replace(" ", " "));
});
if (!isValidName(name)) {
//return fail message
} else {
//return success message
}
function isValidName(name) {
var regex = new RegExp("^[a-zA-Z ]+$");
if (regex.test(name)) {
return true;
} else {
return false;
}
}

Categories