I would like to disallow the user to type comma or dot while typing in the input field of the type number.
I have already searched and found solution, but it does not work.
If I type e.g. point, no matter which of the two solutions below, the input field is cleared.
This is my input field
<input type="number" class="form-control numbersOnly" name="angebot" id="angebot" min="1" step="1" placeholder="<?php the_field('language_shop_detail_button_counter_offer_placeholder', 'option'); ?>">
Those are the 2 approaches that don't work.
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
and
$('.angebotAbgebenContainer #angebot').keyup(function(event) {
var current = $(".angebotAbgebenContainer #angebot").val();
console.log("current", current);
var replaced = current.replace(/\./g, "");
console.log("replaced", replaced);
//replaced = parseInt(replaced);
// $('.angebotAbgebenContainer #angebot').val(replaced);
});
Those are the 2 approaches that don't work. As soon as I make a point, in both approaches, the input field is cleared.
But what I want is, if someone tries to type a point or a comma, it doesn't appear and if someone copy pastes a number, the comma and point must also be gone.
This works for me
Note it is type text
$('#angebot').on("input",function(event) {
var current = $(this).val();
console.log("current", current);
var replaced = current.replace(/[\D\.,]/g, "");
console.log("replaced", replaced);
$(this).val(replaced);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="text" id="angebot" />
If you are going to input numeric values in the input only, might as well disable the inputting of all keys except numeric, like:
$(document).on("keypress keyup blur", ".numbersOnly", function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
Where 48 - 57 represents keycodes, you can find all keycodes here.
Can use prevent default as below, and on change for paste
$(function() {
$('#angebot').on('keydown', function(e) {
if (e.keyCode == 188 || e.keyCode == 110) { // 188 for comma, 110 for point
e.preventDefault();
}
}).on('change', function() {
var self = $(this);
self.html( self.html().replace(new RegExp(',', 'g'),'') ); // Remove all commas.
self.html( self.html().replace(new RegExp('.', 'g'),'') ); // Remove all points
});
})
Related
I have an HTML input element for positive integer numbers. I need to evaluate this input field and ensure that only proper values are inserted.
function exampleFunction(event, element) {
// If event is not backspace and Not a Number
if (event.which != 8) {
//If the event is Not a Number
if (isNaN(String.fromCharCode(event.which))) {
// Cancels the event
event.preventDefault();
}
//If the length reached the limit
else {
var value = document.getElementById(element.id).value;
var maxLength = document.getElementById(element.id).maxLength;
var valueLength = document.getElementById(element.id).value.length;
if (valueLength >= maxLength) {
// Cancels the event
event.preventDefault();
} else {
// Convert the value to a number and back to string. This means leading 0 will be gone.
document.getElementById(element.id).value = Number(value);
}
}
}
};
<input id="exampleInput" type="number" value="0" min="0" step="1" maxlength="5" onkeypress="exampleFunction(event, this)">
purposes:
default value is 0
only numbers shall be accepted
no decimal value .,
no other characters +-e
the input can come from:
typing
copy
backspace and delete can also modify the value
length of input shall also be limited for 5 character length
leading 0 shall be eliminated after a proper new value
Problems:
the default value is 0 and leading zeros are not immediately deleted, only after the second number is typed
with ctrl+v .,+-e characters can be inserted
Question:
Is any better solution for my purposes?
If it is jQuery related, it is also acceptable.
Maybe I am not using the proper event. I tried also to handle the
input event but it is not possible to evaluate the input text.
I am not sure if I make this too complicated, or the solution would be much more complex than I think.
I suggest you to use .addEventListener() instead of the inline event handler.
So to the same input element, you can add more than one event. To do what you wish to do, there are three events implied:
keydown to prevent the not allowed keys
contextmenu for mouse pasting
input to parseInt the value
The below snippet is restricting the input to nubers only. No dot, minus sign, e or whatever except numbers are allowed.
Pasting can be done via [CTRL]+[v] or the mouse contextmenu. In both cases, I assume the previous value of the input should be squarely cleared.
I took the pasted negative numbers case in account using Math.abs().
// Get the element
let myInput = document.querySelector("#exampleInput")
// This event handler only allows numbers, backspace and [ctrl]+[v]
myInput.addEventListener("keydown", function(event) {
console.log("Key:", event.key)
// If this is to be a keyboard paste [CTRL]+[v],
// squarely clears the input value before the paste is done
if (event.ctrlKey && event.key === "v") {
console.log("keyboard paste")
this.value = ""
return;
}
// If the key is not backspace, but is NAN, it is not a number.
// In short, only a number OR a backspace is allowed at this point.
if (event.key !== "Backspace" && isNaN(event.key)) {
event.preventDefault();
console.log(" --------- Event prevented")
}
});
// This handler is for "mouse pastes"
// It squarely clears the input value before the paste is done
myInput.addEventListener("contextmenu", function(event) {
this.value = ""
})
// This handler fixes the value length and parses as a positive integer
myInput.addEventListener("input", function(event) {
console.log("Original value", this.value)
// Get the maxlength attribute value
var maxLength = parseInt(this.maxLength)
// ParseInt the value (will remove any leading zero) and ensure it is positive
// Then keep just the [maxlength] first characters.
var value = Math.abs(parseInt(this.value)).toString().slice(0, maxLength)
console.log("Fixed value", value)
this.value = value;
});
<input id="exampleInput" type="number" value="0" min="0" step="1" maxlength="5">
Here we go with a JQuery solution
Features:
Remove default "0" on focus.
Set maximum length to (5)
Allowed numeric content only and Backspace, Del, Home, End, Arrow-Left, Arrow-Right,
ctrl+v, ctrl+c, ctrl+a buttons.
Check if the copied text contains any numeric value and collect it and remove non-numeric values.
Check if pasted text length + current value length are meeting maximum length
$(document).ready(function() {
//Remove default "0" ONLY! when focus at the input.
$("#exampleInput").on('focus', function() {
var oldval = $("#exampleInput").val();
if (oldval < 1) {
$("#exampleInput").val("");
}
});
/* SET CTRL+V , CTRL+C funciton */
var ctrlprs = false,
ctrlk = 17,
mccmd = 91,
vk = 86,
ak = 65,
ck = 67;
$(document).keydown(function(e) {
if (e.keyCode == ctrlk || e.keyCode == mccmd) ctrlprs = true;
}).keyup(function(e) {
if (e.keyCode == ctrlk || e.keyCode == mccmd) ctrlprs = false;
});
//Listen to the input in keydown
$("#exampleInput").on('keydown', function(e) {
var txt = $("#exampleInput").val();
//exceptions for [b-space,end,home,left,right,del]
var keys = [8, 35, 36, 37, 39, 46];
var rgx = $.inArray(e.which, keys) < 0;
var cnvrt = String.fromCharCode(e.which);
/* allow CTRL + "a or c or v" */
if (ctrlprs && ((e.keyCode == ck) || (e.keyCode == ak) || (e.keyCode == vk))) {
} else if ((txt.length == 5) || (cnvrt.match(/[^0-9]/)) || (e.shiftKey)) {
if ((rgx)) {
e.preventDefault();
/* prevent all text except numbers, and set max input value length to (5) */
}
}
});
/*Bind a paste function to check if clipboard data met with requirements or not.*/
$("#exampleInput").on('paste', function(e) {
var oldl = $("#exampleInput").val();
var oldval = e.originalEvent.clipboardData.getData('text');
if (oldval.match(/[0-9]{1,5}$\d/g)) {} else {
//remove all non-numeric text from clipboard text.
var newvar = oldval.replace(/\D/g, "");
setTimeout(function() {
//check if ( clipboard[Numeric only] + input value ) length equals or less than (5).
var totlen = oldl.length + newvar.length;
if (newvar.length > 0 && totlen <= 5) {
$("#exampleInput").val(oldl + newvar);
} else {
//if total length is more than (5) keep the input value before paste.
console.log("total length is : " totlen);
$("#exampleInput").val(oldl);
}
}, 1);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="exampleInput" type="number" value="0" min="0" step="1" maxlength="5">
When I'm giving input type number the letter e and special charecters are also displaying in input field. I want to display only digits. How to block them?
<input type="number">
Try preventing the default behaviour if you don't like the incoming key value:
document.querySelector(".your_class").addEventListener("keypress", function (evt) {
if (evt.which != 8 && evt.which != 0 && evt.which < 48 || evt.which > 57)
{
evt.preventDefault();
}
});
// 0 for null values
// 8 for backspace
// 48-57 for 0-9 numbers
<input type="number" class="your_class">
A simple solution which I used in React.
onKeyDown={(evt) => ["e", "E", "+", "-"].includes(evt.key) && evt.preventDefault()}
You can block entering those chars with keydown event
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"+",
"e",
];
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" />
but the user can still enter them if s/he does a copy/paste (or through the console). To prevent copy/paste, you can do a replace on the entered value [*].
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"+",
"e",
];
inputBox.addEventListener("input", function() {
this.value = this.value.replace(/[e\+\-]/gi, "");
});
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" />
* You can't really get the entered value on an input field with type set to number. You can get the entered value as long as it is a number, that is, the value passes the internal number check. If the user copy/paste 1e, suggested solution will fail.
What happens when you enter 1e is that, input field checks if it's a number, and if it's not (1e is not) it throws a warning:
The specified value "1e" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?
and the value property is set to "".
If you check the field's properties, you'll find valueAsNumber property. If the entered value is a number, input field parses the value and stores it in valueAsNumber. Since 1e is not a number, it evaluates to NaN, and NaN is assigned to valueAsNumber and value is set to "". Though you still see 1e on the input field.
I've asked a question related to this problem, but no solution yet.
Get the entered value on number input field, not the parsed
Instead on trying to block values, you can try to replace values that are non numeric.
If you choose to handle keycodes, you will have to handle numKeys, numPad, shift +, crtl + etc and trying to refresh while focus is inside textbox will also fail. Prevent Default will stop lot more than incorrect values.
$("#input").on("input", function() {
var nonNumReg = /[^0-9]/g
$(this).val($(this).val().replace(nonNumReg, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="input" />
<div class="alert"></div>
Following form from the answers above, most of the examples above cover it, i just noticed that when inputting "E" this is still allowable so i think its best to add this into the array. I am using Jquery 3.3.1 in this example.
Also that way whatever you enter into the array will be prevented from being keyed in into the input box
Note - take the 'elementid' as the id of the element you want to apply this to
similarly if you want to apply this to all inputs that are type number in JQuery --> $("input[type='number']")
var invalidChars = ["-", "e", "+", "E"];
$("input[type='number']").on("keydown", function(e){
if(invalidChars.includes(e.key)){
e.preventDefault();
}
}):
This sample above should work on all inputs with a type of number and prevent the characters "-", "e", "+" and "E" from being keyed into the input.
UPDATE
Just also notices that you are able to enter '.' as they represent decimal points which is valid for numbers. I was using this validating a telephone number and obviously (for UK) there is no '.' so that may also be another character to add to your array.
Here's a pretty concise solution using jQuery based on some of the other solutions:
$("input[type=number]").on("keydown", function(e) {
var invalidChars = ["-", "+", "e"]; //include "." if you only want integers
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
You can do it easily using jQuery
Try this code
$(function() {
$("#input").keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
$(".alert").html("Enter only digits!").show().fadeOut(2000);
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="input" />
<div class="alert"></div>
$("#input").on("input", function() {
var nonNumReg = /[^0-9]/g
$(this).val($(this).val().replace(nonNumReg, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="input" />
<div class="alert"></div>
You can check it if it's a number or not.
// Restrict e, -, + for html input number
$(document).on('keypress', ':input[type="number"]', function (e) {
if (isNaN(e.key)) {
return false;
}
});
Since OP's question was tagged with 'angularjs', the cleanest solution would probably be to use a directive. Several solutions for this approach have previously been explained here:
angularjs: allows only numbers to be typed into a text box
JQuery
You can also use the following code if you want to accept decimals(.)
$('input[Type="Number"]').keypress(function (e) {
if ('0123456789'.indexOf(e.key)!=-1){}
else if (e.key=='.' && this.value!='' && (this.value.match("\.") || []).length==0){}
else{e.preventDefault();}
});
Here is React solution, hope it will help somebody
const numberInputInvalidChars = ['-', '+', 'e'];
<input
type="number"
onKeyDown={(e) => {
if (numberInputInvalidChars.includes(e.key)) {
e.preventDefault();
}
}}
></input>
With onKeyUp, onKeyPress or onKeyDown events the same can be restricted.
onKeyDown = {
(e) => ["e", "E", "+", "-"].includes(e.key) && e.preventDefault()
}
Yo can Block by using some JQuery codes
$('input[Type="Number"]').keypress(function (e) {
if ('0123456789'.indexOf(e.key) == -1) {
e.preventDefault();
}
});
This will affect on all Numeric typed Input
I'm not sure the details of your use case, but you may not need to do a lot to handle these yourself. For starters, you can set a min, which can be used to prevent negatives, as well as a max value and a step value if that's useful. It turns out the default step is 1, so it requires integers unless you specify a decimal step value.
When it comes to dealing with the "e" in numbers, you can use Number() to convert text to a number, and it'll automatically convert the "e", as well as any "+" sign:
> Number("5e3")
5000
> Number("+42")
42
If you really need the submitted value to be normalized, you can convert it back in place. I think probably the most user friendly time to do it would be on blur:
input.addEventListener('blur', () => {
if (input.value !== '' && input.checkValidity()) {
input.value = Number(input.value);
}
});
in the input of numeric type the events for characters with value different from [0-9] is an object
with
event.target.value: ""
so just prevent events that have no value
if (!event.target.value) {
event.preventDefault();
};
If you want + sign in your phone number field then you can use this code.
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"e",
];
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" />
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');;
});
Is there a way to block users from writing specific characters in input fields? I tried the code below, but when a user enters disallowed characters, they appear for a brief period before disappearing. I want the input to remain unchanged when invalid characters are written.
I want to use onchange because other restriction methods do not seem to work on mobile devices. The problem I want to solve is that characters appear briefly before being removed.
function checkInput(ob) {
const invalidChars = /[^0-9]/gi;
if(invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars, "");
}
};
<input class="input" maxlength="1" onChange="checkInput(this)" onKeyup="checkInput(this)" type="text" autocomplete="off" />
you can use try this,
$('.input').keyup(function () {
if (!this.value.match(/[0-9]/)) {
this.value = this.value.replace(/[^0-9]/g, '');
}
});
SEE THIS FIDDLE DEMO
Updated :
You can try this Code,
$(document).ready(function() {
$(".input").keydown(function (e) {
// Allow: backspace, delete, tab, escape and enter
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
SOURCE
SEE UPDATED FIDDLE DEMO
UPDATED FOR ANDROID:
<EditText
android:id="#+id/editText1"
android:inputType="number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="58dp"
android:layout_toRightOf="#+id/textView1"
android:maxLength="1" >
</EditText>
I think it may help you... using android:inputType="number" you can do that.
A combination of keypress and paste events does a trick:
var text = document.getElementById('text');
text.onkeypress = text.onpaste = checkInput;
function checkInput(e) {
var e = e || event;
var char = e.type == 'keypress'
? String.fromCharCode(e.keyCode || e.which)
: (e.clipboardData || window.clipboardData).getData('Text');
if (/[^\d]/gi.test(char)) {
return false;
}
}
<input class="input" maxlength="10" id="text" type="text" autocomplete="off" />
This code prevents from typing or pasting anything but a number. Also no blinking and invalid characters don't show up.
Works in IE7+.
Demo: http://jsfiddle.net/VgtTc/3/
All answers given so far suffer from at least one of the following accessibility issues:
They validate key codes, which does not work with non-QWERTY keyboard layouts.
They do not cover all input methods; especially drag&drop is often forgotten.
They alter the value, which resets the position of the caret.
They use the pattern attribute, but this does not provide feedback until the form is submitted.
Wouldn't it be a much better idea to actually validate the input before it's inserted?
The beforeinput event fires before the input's value is changed. The event has a data property which describes the content that the user wants to add to the input field. In the event handler, you simply check the data attribute, and stop the event chain if it contains disallowed characters.
We end up with the following very simple, very short code.
const input = document.getElementById("input");
const regex = new RegExp("^[0-9]*$");
input.addEventListener("beforeinput", (event) => {
if (event.data != null && !regex.test(event.data))
event.preventDefault();
});
<label for="input">Enter some digits:</label>
<input id="input" />
Some closing notes:
Accessibility: Provide a clear explanation of what input format is expected from the user. For example, you can use the title attribute of the input to show a tooltip explaining the expected format.
Security: This is client-side validation, and does not guarantee that the pattern is enforced when the form is sent to a server. For that, you'll need server-side validation.
Here's a little hack you could try: DEMO
What it does is that it colors every input text white and then changes it back to black if it suits your requirements. If you could live with the bit of lag that occurs when you enter a valid character.
function checkInput(ob) {
var invalidChars = /[^0-9]/gi
if (invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars, "");
}
else {
document.getElementById('yourinput').style.color = '#000';
}
};
function hideInput(ob) {
document.getElementById('yourinput').style.color = '#FFF';
};
html
<input id="yourinput" class="input" maxlength="1" onKeydown="hideInput(this)" onKeyup="checkInput(this)" type="text" autocomplete="off" />
css
input {color:#FFF;}
check this code,
$('.input').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
<input id="testInput"></input>
<script>
testInput.onchange = testInput.oninput = restrict;
function restrict() {
testInput.value = testInput.value.replace(/[^a-z]/g, "");
}
</script>
I came up with something slightly different. oninput instead of onkeyup/onkeydown, and onchange instead of onpaste.
I restrict invalid characters on both keypress and paste events like:
<input type="text" onkeydown="validateKey(event)" onpaste="validatePaste(this, event)">
And define functions to handle these events inside tab or a separate javascript file:
<script>
function validateKey(e) {
switch(e.keyCode) {
case 8,9,13,37,39:
break;
default:
var regex = /[a-z .'-]/gi;
var key = e.key;
if(!regex.test(key)) {
e.preventDefault();
return false;
}
break;
}
}
function validatePaste(el, e) {
var regex = /^[a-z .'-]+$/gi;
var key = e.clipboardData.getData('text')
if (!regex.test(key)) {
e.preventDefault();
return false;
}
}
</script>
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/