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()
}
Related
Ok Well. I want to restrict input field to accept only numbers with maxlength 5 characters.
My Try:
HTML
<input type="number" maxlength="5" onKeyDown="numbersOnly(event);/>
<input type="text" pattern= "[0-9]" onKeyDown="numbersOnly(event);/>
Javascript
function numbersOnly(event,length)
{
return event.ctrlKey || event.altKey
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46)
|| (event.keyCode>47)&&(event.keyCode<=57) ;
}
All works in firefox. But when i check with safari ipad, it accepts special characters like ()#!#$&. I used alert function for debugging. It returns same keyCode for # and 2 , 3 and # and so on. I tried keyUp,keyPress events and event.charCode,event.which,event.key. Nothing works
So how to differentiate it and i need support for backspace , enter , delete, arrow keys also.
I've made this once and haven't been able to break it. Tested on iPad.
// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
this.value = this.value.replace(/[^0-9]+/g, '');
if (this.value < 1) this.value = 0;
});
// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});
This also accounts for copy/paste and drag and drop text, which people often forget. You can add the max-length to the onchange.
Using type="number" on an input prevents you from reading non-numerical input values via input.value (it will then return an empty string) and thus eliminates the possibility of filtering invalid user input (+-.e) while keeping the valid numbers. Thus you have to use type="text". Example:
$('.input-number').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="input-number" type="text" maxlength="5">
If you want the text-cursor not to move when pasting or typing invalid input, have a look at my answer to a similar question here: HTML input that takes only numbers and the + symbol
Be careful the iOS keyCodes are not the same desktop computers. See IOS keyCodes in Javascript
<input type="number" maxlength="5" onkeypress="numbersOnly(event);/>
var numbersOnly = function(event) {
if(event.keyCode >= 48 && event.keyCode <= 57) {
return false;
} else {
event.preventDefault();
}
}
If you want to enter the only numbers in input type number fields. this will be helpful, It will work on iPhone and iPad as well.
$(document).on('keypress', 'input[type="number"]', function (event) {
return event.code.includes('Digit') || event.code.includes('Numpad') || event.code.includes('Period');;
});
I made a function to prevent a user from entering anything other than numbers into a field (but allows useful keys like "backspace", "enter", etc ...)
Here a jsFiddle for the example: http://jsfiddle.net/cWHRp/1/
And the javascript code:
$('input').on('keypress', function (e) {
if (
// Allow "backspace", "tab", "enter", "escape" and "delete"
($.inArray(e.keyCode, [8, 9, 13, 27, 46]) !== -1) ||
// Allow "shift + decimal point" (= delete on numpad)
(e.shiftKey === true && e.keyCode == 110) ||
// Allow "Ctrl + A" and "Ctrl + C"
(e.ctrlKey === true && ($.inArray(e.keyCode, [65, 67]) !== -1)) ||
// Allow "end", "home", "left arrow", "up arrow", "right arrow" and "down arrow"
(e.keyCode >= 35 && e.keyCode <= 39) ||
// Allow "shift + classic numbers"
(e.shiftKey === true && e.keyCode >= 48 && e.keyCode <= 57) ||
// Allow numbers on numpad
(e.keyCode >= 96 && e.keyCode <= 105)
) {
return;
}
e.preventDefault();
});
It works well, even with shift + number. But I don't know how to detect that capsLock is ON when the user is typing on the keyboard.
Have you any idea to solve this problem please?
Thank you in advance!
Don't do this, this creates more problem than it solves. Here are some better solutions:
a) <input type="number" />
b) <input type="text" pattern="\d+" />
c) .replace(/[^\d]/g,'') in a change (or keyup) event listener
d) masked-input plugins
e) client + server-side validation (which you should use anyway)
OK, so first off as others have mentioned: why are you doing this?. #pawel has suggested some better approaches.
That said, using the KeyboardEvent.getModifierState() method, you can do the following:
$('input').on('keypress', function(e) {
var isCapsLock = e.originalEvent.getModifierState("CapsLock");
...
});
You could use oninput event (taking care of paste value from contextmenu) and just use a regex to match all not numeric characters:
SEE DEMO
$('input').on('input', function (e) {
this.value = this.value.replace(/\D/g,'');
});
You could still use onkeyup/onpaste event instead, for older browsers which don't support oninput event.
I am doing validation on an input type='text' element. I have wired up the 'paste' and the 'keydown' events to trap the input and restrict it to just numbers. The keydown seems to work without a hitch, however, I could not seem to get any of the browsers to actually NOT PASTE the text into the field (I see that there is a beforepaste event, which may be the ticket -- however it appears to not be supported by firefox. In the end, I resulted to just blanking out the input if the value was not a number. This causes a momentary flicker, but seems to work.
Is there a cleaner way to do this? Am I missing something? Is there anyway to prevent the flicker? I know the HTML5 has a type='number', but I'm not ready to go there yet.
<input type="text" id="number" />
<script type="text/javascript">
$(document).ready(function () {
enableNumericOnlyEntry("#number");
function enableNumericOnlyEntry(object) {
$(object).bind('paste', numericOnlyPaste);
$(object).bind('keydown', null, numericOnlyKeyDown);
function numericOnlyPaste(event) {
var inputText = "";
var element = event.target;
setTimeout(function () {
var text = $(element).val();
if (isNaN(text)) {
$(element).val("")
return false;
}
}, 0);
}
function numericOnlyKeyDown(event) {
// Allow: backspace, delete, tab, escape, and enter
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A/a
(event.keyCode == 65 || event.keyCode == 97) && (event.ctrlKey === true) ||
// Allow: Ctrl+C/c
(event.keyCode == 67 || event.keyCode == 99) && (event.ctrlKey === true) ||
// Allow: Ctrl+V/v
(event.keyCode == 86 || event.keyCode == 118) && (event.ctrlKey === true) ||
// Allow: Ctrl+X/x
(event.keyCode == 88 || event.keyCode == 120) && (event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return true;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
return false;
}
}
}
}
});
I've used this project to create a field that is a masked edit box, you could remove the underscore to it also so it doesn't look like a masked edit. Really easy to use: http://digitalbush.com/projects/masked-input-plugin/
then you'd use something like $("#box").mask("9999999"); and your good to go, works great!
HTML5's <input type="number"> is really where you want to go with this. If you're working with browsers that support it (basically everything except Safari and old versions of IE), it does everything you want.
That said, why not register an onpaste handler so you can reduce pasted content to just numbers after the user pastes?
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('');
}
});
});
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(); }
});