Remove numeric'
So my problem is that I have written a little charset function, that takes all numbers from 0-9, and atm I have just console.log'ged them, but when I have tried to remove the numeric' keys from 0-9 when typed into my input, it won't work. This code will show it as a return false.
function reg(e) {
const char = e.which;
if (char >= 48 && char <= 57) { return false }
}
return (
<>
<form onSubmit={validate}>
<input type="text"
onKeyDown={reg}
value={usernameValue}
placeholder="name"
onChange={setUsernameValue} />
Instead of returning false, you should prevent the default event behaviour. This is a very common trick in JS event handlers.
It looks like this:
function reg(e) {
const char = e.which;
if (char >= 48 && char <= 57) { e.preventDefault() }
}
Related
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.
How can I make contenteditable elements only allow entry of numeric values?
I tried to use something like:
onkeypress='return event.charCode >= 48 && event.charCode <= 57'
...on elements that are contenteditable, but it still allows entry of alphabetic characters.
Thanks!
Why not just use an input?
<input type="number">
If you still want to use contenteditable, you can add an event listener like so:
$("#myeditablediv").keypress(function(e) {
if (isNaN(String.fromCharCode(e.which))) e.preventDefault();
});
This will block all characters that are not numbers (0-9)
Salaam
This will allow only numbers
$('[contenteditable="true"]').keypress(function(e) {
var x = event.charCode || event.keyCode;
if (isNaN(String.fromCharCode(e.which)) && x!=46 || x===32 || x===13 || (x===46 && event.currentTarget.innerText.includes('.'))) e.preventDefault();
});
I have also tested decimals. There are three major conditions to get allowed
Is a Number and Not delete button
Not Space
Not Enter Button
Allow Decimal point only once
Let me know if you face any bug in comments
Thank you
If you want to enter only 0-9 in contenteditable div then you can use this code. This code also prevent user to copy paste into the field
<div contenteditable id="myeditablediv" oncopy="return false" oncut="return false" onpaste="return false">10</div>
Javascript
$("#myeditablediv").keypress(function(e) {
if (isNaN(String.fromCharCode(e.which))) e.preventDefault();
});
if you want to enter decimal points instead of a number then you can use this javascript code
$("#myeditablediv").keypress(function(e) {
var x = event.charCode || event.keyCode;
if (isNaN(String.fromCharCode(e.which)) && x!=46) e.preventDefault();
});
Allowing numbers, the point, the backtracking
<div
on:keydown={(event) => {
if (
event.code.includes('Digit') ||
event.code === 'Backspace' ||
event.code === 'Period'
) {
console.log(e)
} else {
event.preventDefault()
}
}}
>
foo
</div>
If you want to allow only numbers, you can use :
if (e.which < 48 || e.which > 57) e.preventDefault();
If you want to enable pad numbers, use this code :
if (!e.key.match(/^[0-9]/g) && e.keyCode !== 8 && e.keyCode !== 46) {
e.preventDefault();
}
The regex starts with '^' to prevent F5 to works for example. We add e.keycode 8 and 46 to avoid the prevent default on backspace/delete
This method doesn't allow decimals, you'll need to modify regex for it
Just expanding on ElChino3312's answer to include some additional accepted keys (numpad, arrows and delete) and excludes period as I'm not allowing decimals in my case:
if (!(event.code.includes('Digit') || event.code.includes('Numpad')
|| event.code === 'ArrowLeft' || event.code === 'ArrowRight'
|| event.code === 'Backspace' || event.code === 'Delete'))
{
event.preventDefault()
}
I'm trying to creat a mask for comma separated values for my inputs, but I'm having dificulties.
Can you guys help me?
Here is my current mask:
<script>
$(document).on("keyup keydown keypress", "commaseparated", function (e) {
if (!$(this).val().match(/^([0-9]{0,1})(,[0-9]{1,}){1,}?$/g)) {
e.preventDefault();
}
});
</script>
<input type="text" class="commaseparated" />
<!-- example input would be
1235 <- single number
or
2654,524874,5456 <- many numbers
-->
Thanks in advance :)
EDIT
Well, this is not exactly a mask. What I want is that the user can only insert numbers and commas, e.g:
123 -> allowed
123,123 -> allowed
123,, -> not allowed
123,letters -> not allowed
You can use RegExp /(,|\D)(?=\1)|^[,\D]|[^,\d]$/g to match comma or non-digit character followed by comma or non-digit character or comma or non-digit at beginning of string or last character of string is not a digit or comma, replace match with empty string.
$(".commaseparated").on("input", function(e) {
$(e.target).prop("value", function(_, val) {
return val.replace(/(,|\D)(?=\1)|^[,\D]|[^,\d]$/g, "");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="commaseparated"/>
Please, give a try to the below jquery.
//We need to capture the keypress event, as this is triggered before the value is displayed in the text box.
$(document).on("keypress", ".commaseparated", function (e) {
var currentValue = $(this).val();
//If the value is empty, let user enter numerals.
if(currentValue == "" && e.keyCode >= 48 && e.keyCode <= 57) {
return true;
}
else {
//If some value is there, get the last character.
var lastChar = currentValue.substr(currentValue.length - 1);
//If the last character is comma, let user enter numerals.
if(lastChar == "," && e.keyCode >= 48 && e.keyCode <= 57){
return true;
}
//If the last character is comma, deny entering comma again.
else if(lastChar == "," && e.keyCode == 44){
return false;
}
//If the control reaches here and as last character could only be numeral, let user enter only comma or numerals.
else if (e.keyCode == 44 || (e.keyCode >= 48 && e.keyCode <= 57)) {
return true;
}
// for everything else, return false.
else{
return false;
}
}
});
Find the jsfiddle here.
http://jsfiddle.net/WhP8q/
I'm trying to restrict input to alpha numeric, 0-9, A-Z,a-z.
The ASCII table i'm referencing: http://www.asciitable.com/
Here is what I have so far
$(function() {
$("input").bind("keydown paste", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var c = code;
var letterAllowed = ((c > 47 && c < 58) || (c > 64 && c < 90) || (c > 96 && c < 123))
if (code > 32 && !letterAllowed) {
return false;
}
});
});
right now, the tilde (~) character is prevented from getting input into the field, but other special / shift characters such as !##$% all get entered into the text field.
I'm pretty sure my logic is sound, but my issue is with some misunderstanding of javascript bindings? idk
Preventing character input for only some cases is very complicated in javascript, as in the keypress event (the one you'd want to prevent) you do not know the afterwards value of your input, but only the keycode of the pressed key (and not even the resulting char for sure). Also, you will need to care about special keys like or .
I'd recommend something like this:
$("input").on("keypress keyup paste", function(e) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});
In case of restrict the character you enter, You can replace the character which is not alphanumberic.
<input type='text' id="txtAlphaNumeric"/>
<input type='text' id="txtNumeric"/>
<input type='text' id="txtAlphabet"/>
<script type="text/javascript">
$(function() {
$('#txtNumeric').keyup(function() {
if (this.value.match(/[^0-9]/g)) {
this.value = this.value.replace(/[^0-9]/g, '');
}
});
$('#txtAlphabet').keyup(function() {
if (this.value.match(/[^a-zA-Z]/g)) {
this.value = this.value.replace(/[^a-zA-Z]/g, '');
}
});
$('#txtAlphaNumeric').keyup(function() {
if (this.value.match(/[^a-zA-Z0-9]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
}
});
});
</script>
Answer taken from: jquery allow only alphanumeric
Turns out, I need to do the following:
$("input").keypress(function(e){
var code = e.charCode;
charCode will give the actual character code of the typed letter, rather than the ascii code of the last pressed key
see http://api.jquery.com/keypress/
I would like have always only float value with dot (not comma) in my inputs.
<input type="text" class="dot"> <br />
<input type="text" class="dot"> <br />
<input type="text" class="dot"> <br />
$('.dot').keydown(function(){
$(this).val($(this).val().toString().replace(/\,/g, '.'));
})
this replace comma to dot, but this should not be have > 1 dot and others... This should be accept only [0-9] and .
if i type a different value than other [0-9] and . then this value should be remove - ''.
How can i make it?
http://jsfiddle.net/ZtkBW/
Hiya demo http://jsfiddle.net/9Ry9t/ or http://jsfiddle.net/ZtkBW/2/ or http://jsfiddle.net/HJnLD/
Bit different from your solution but if you keen to use this, it will not allow any characters to type in the text box.
The solution does full validation for numbers and for float it will not take (dot)
code sample
$('.number').keypress(function(event) {
if(event.which < 46
|| event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46
&& $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
});
Here's a really terrible if statement to circumvent the fact that parseFloat can parse the first number it finds in a string and indexOf only returns the first index of a character (not all indexes).
It would probably be smarter to store the value of $(this).val() in a variable but I'll leave that as an exercise to the reader. (don't have time right now)
if(!isNaN(parseFloat($(this).val()) && $(this).val().indexOf(".") > -1 && $(this).val().indexOf(".") == $(this).val().lastIndexOf(".")) {
// do something, your value is a valid float
}
You can try this :
http://jsfiddle.net/ZtkBW/5/
var parseInput = function(val) {
var floatValue = parseFloat(val);
return isNaN(floatValue) ? '' : floatValue;
}
$('.number').keyup(function(){
var value = $(this).val()+'';
if (value[value.length-1] !== '.') {
$(this).val(parseInput(value));
}
}).focusout(function(){
$(this).val(parseInput($(this).val()+''));
})
I used keyup to avoid displaying the character if invalid.
As mentionned in comments, I also used focusout.
I do not parse if the last entered character is '.' because you will not be able to enter a decimal value.
$('.dot').keydown(function(){
$(this).val($(this).val().toString().replace(/^[0-9]\./g, ',')
.replace(/\./g, ''));
})
How it behave
I'm not really sure what you want to do
but how about this
$(this).val(parseFloat($(this).val()) || 0);
I had the same problem - needed a text input to accept only an integer or a decimal input (only one .)
Had to mix a few solutions, but this is working now:
$(".dot").keyup(function(event){
this.value=this.value.replace(/[^0-9.]/g,'');
var parts=this.value.split(".");
var decimal=false;
for(var part in parts)
{
if(part==0) this.value=parts[part];
if(part==1) this.value=this.value+"."+parts[part];
}
});
Try this :
$("#txtSellerPrice").keydown(function (e) {
if (e.keyCode == 110 && this.value.split('.').length == 2)
{
e.preventDefault();
}
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190,110]) !== -1 || (e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) || (e.keyCode >= 35 && e.keyCode <= 40)) { return; } if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105))
{ e.preventDefault(); }
});