how to validate predefined value using javascript - javascript

i have a input textbox in html and i want to allow the user just 'Y' or 'N' and if he tries to enter any other character then it should show an alert dialog box. so can anyone help me into dis??

jQuery version
$('input').keypress( function( e ){
$(this).val('');
var code = e.which || e.keyCode ;
if ( !( code == 89 || code == 121 ||
code == 78 || code == 110 ) ){
alert('you entered wrong key');
e.preventDefault();
}
});
check it on jsfiddle http://jsfiddle.net/TTgKF/
inline javascript version
<input id="keypress" onkeypress="return allowYN( this, event );" />
and allowYN define as
function allowYN( el, event) {
event = event || window.event;
var charCode = (event.which) ? event.which : event.keyCode;
el.value = '';
isYN = (charCode == 89 || charCode == 121 ||
charCode == 78 || charCode ==110 );
if ( !isYN ) {
alert('you entered wrong key');
}
return isYN;
}
You can add exception for Delete key (46), Backspace key (8) ..

Assuming you're able to get the HTML element by ID, this would check the #myInput element and only accept Y or N.
if ((document.getElementById('myInput').value == 'Y') ||
(document.getElementById('myInput').value == 'N')) {
// Do stuff if it's correct.
} else {
alert("You're doing it wrong!");
}

As previously noted, the best option is to use radio buttons:
<input type="radio" name="yn" value="Y">Y<br>
<input type="radio" name="yn" value="N">N<br>
Then either set one as selected or check on submit that one is selected. Alternatively, you can use scripted input elements, but it is not sensible:
<script>
function validateYN(element) {
var errNode = document.getElementById(element.id + '_err');
if(/^[YN]$/.test(element.value)) {
errNode.innerHTML = '';
} else {
errNode.innerHTML = "You must enter Y or N";
}
}
</script>
Please enter Y or N: <input name="foo" id="foo" onchange="validateYN(this);"
onblur="validateYN(this);">
<span id="foo_err"></span>

you could also try this
$("input").live('keypress', function(e) {
if!( code == 89 || code == 121 ||
code == 78 || code == 110 ) ) {
e.preventDefault();
}
else //your code

<html>
<head>
<script type="text/javascript">
function keyPressed(evt)
{
var theEvent = evt || window.event;
var k = theEvent.keyCode || theEvent.which;
if(k == 89 || k == 78 || k == 8 || k == 46)
return true;
else{
alert("Your Message");
evt.preventDefault();
return false;
}
}
</script>
</head>
<body>
<input type="text" onkeydown="keyPressed(event)" />
</body>
</html>

Related

Regex - Allow Numbers 0-9, Backsapce and 1 dot Javascript

I have a function which acts on keydown event and I want it to allow only numbers, backspace and 1 dot. I can't make it work. Here is what I tried:
$('#input[type="number"]').keydown(function(e) {
this.value = this.value.toLowerCase();
var regex = new RegExp("^[0-9.,\b]+$");
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (!regex.test(key)) {
console.log('stop now')
e.preventDefault();
return false;
}
});
It still prevents dot, but allows numbers. I think my Regex is wrong and needs a tweak.
The comment is gone, but some user suggested that it could be to do with the escaping of the . and , ?? Any ideas?
Use keypress insetead of the keydown event. There are different charcodes sent for some keys for the keydown event. The dot is one of them, sending code 190 instead of the ASCII 46. You can play around with it here.
you can use this instead of using regex. I think This will help you
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" language="jscript">
function fncInputNumericValuesOnly() {
if (!(event.keyCode == 32 || event.keyCode == 46 || event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || event.keyCode == 51 || event.keyCode == 52 || event.keyCode == 53 || event.keyCode == 54 || event.keyCode == 55 || event.keyCode == 56 || event.keyCode == 57))
{
event.returnValue = false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtEmpName" onkeypress="fncInputNumericValuesOnly()" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
My answer comes a little late but here I've changed your code to something which may work for you:
var valid_value = '';
$('#input[type="number"]').keyup(function(e) {
var regex = new RegExp(/^[0-9]*\.?[0-9]*$/);
if (!regex.test(this.value)) {
this.value = valid_value;
console.log('stop now');
} else {
valid_value = this.value;
}
});
Have you ever tried something like that?
Of course is not perfect but you can assume it as a starter point:
var whitelist = /^\d+\.?\d+?[\b]?$/;
function testInput() {
var val = document.getElementById('val').value;
var res = document.getElementById('res');
if(whitelist.test(val)) {
res.innerText = 'YEP';
} else {
res.innerText = 'NOOPE';
}
}
<input onchange="testInput()" type="text" id="val"/>
<h1 id="res"></h1>
This is what I came up with in the end. A little manual but does the trick!
$('#input[type="number"]').keydown(function(e) {
if (!(e.keyCode == 190 || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 13 || e.keyCode == 32 || e.keyCode == 46 || e.keyCode == 48 || e.keyCode == 49 || e.keyCode == 50 || e.keyCode == 51 || e.keyCode == 52 || e.keyCode == 53 || e.keyCode == 54 || e.keyCode == 55 || e.keyCode == 56 || e.keyCode == 57)) {
e.returnValue = false;
e.preventDefault();
return false;
}
});
A bit late to the party, but this would work.
edit: click run code snippit before you downvote
var onlySome = restrictKeys([8,190]) // allow the dot
// decorate the jquery function with some functional goodness
$('input[type="text"]').keydown(onlySome(function(e) {
stackLog(['key alowed', e.which, String.fromCharCode(e.which)]);
}));
// functional function to partially apply restricted keys and callback functiion
function restrictKeys(keys) {
return function(fn) {
return function(e) {
// all codes between 48 and 57 are number and cool to leave in, then just filter out our array
if ((e.which < 48 || e.which > 57) && keys.indexOf(e.which) < 0) {
stackLog(['nope', e.which, String.fromCharCode(e.which)]);
e.preventDefault();
return false
}
return fn.call(this, e);
}
}
}
function stackLog(log) {
var _console = document.querySelector('#console');
_console.innerHTML = JSON.stringify(log) + '\n' + _console.innerHTML;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="enter text here">
<pre id="console"></pre>

JS function to allow enter only letters and white spaces

I need a jquery or js function to only allow enter letters and white spaces.
Thanks in advance.
page:
<p:inputText onkeypress="onlyLetter(this)">
function:
function onlyLetter(input){
$(input).keypress(function(ev) {
var keyCode = window.event ? ev.keyCode : ev.which;
// code
});
}
The following code allows only a-z, A-Z, and white space.
HTML
<input id="inputTextBox" type="text" />
jQuery
$(document).on('keypress', '#inputTextBox', function (event) {
var regex = new RegExp("^[a-zA-Z ]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
Note: KeyboardEvent.which is deprecated as of Jan. 1, 2020
Just use ascii codes (decimal values) of keys/digits that you want to disable or prevent from being work. ASCII Table .
HTML :
<input id="inputTextBox" type="text" />
jQuery :
$(document).ready(function(){
$("#inputTextBox").keydown(function(event){
var inputValue = event.which;
// allow letters and whitespaces only.
if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
});
});
jsFiddle Demo
First off, I have little experience in jQuery and will provide a vanilla javascript example. Here it is:
document.getElementById('inputid').onkeypress=function(e){
if(!(/[a-z ]/i.test(String.fromCharCode(e.keyCode))) {
e.preventDefault();
return false;
}
}
Tweaking Ashad Shanto answer a bit. Notice you cant type in y and z if you use the script. You have to change the inputValue from 120 to 123. Here is the ASCII table reference: http://ee.hawaii.edu/~tep/EE160/Book/chap4/subsection2.1.1.1.html Use the script below to type in all the letters, space and backspace.
<script>
$(document).ready(function(){
$("#inputTextBox").keypress(function(event){
var inputValue = event.which;
// allow letters and whitespaces only.
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
console.log(inputValue);
});
});
</script>
you could use this simple method, that I took from this post
<input type="text" name="fullName" onkeypress="return (event.charCode > 64 &&
event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)"
placeholder="Full Name">
jQuery
var letters = /^[A-Za-z ]+$/;
var city_input="";
$(document).ready(function(){
$("#city_name").on("input", function(){
var city_value=$(this).val();
if(city_value==="")
{
city_input=city_value;
}
else if(city_value.match(letters)===null){
$(this).val(city_input);
}
else{
city_input=city_value;
}
});
});
Here is the code which you can understand easily and can modify for any character char exception.
I include the exception for BACKSPACE.
Likewise you can give the exception by including the keycode inside the statement.
var c= ((e.which>=65 && e.which<91) || (e.which==8 /**Here 8 if for the Backspace**/) || (e.which=="your key code"))
https://gist.github.com/SathishSaminathan/e3c509243ead20fcae26c87fdd6f78fd
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<br/>
Enter Only Alphabate: <input id="txtName" name="lname">
<script>
$('#txtName').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z \s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
else
{
e.preventDefault();
alert('Please Enter Alphabate');
return false;
}
});
</script>
</body>
</html>
For me, adding a space inside input tag after z worked.
<p:inputText onkeydown="return /[a-z ]/i.test(event.key)">
function ValidateAlpha(evt) {
var keyCode = (evt.which) ? evt.which : evt.keyCode if (
(keyCode < 65 || keyCode > 90) &&
(keyCode < 97 || keyCode > 123) &&
keyCode != 32 &&
keyCode != 39
)

jquery - How do I add an alert message to this jquery code base?

The Question
To help avoid end-user confusion, I want to add an alert message that pops up if/when the user clicks any other key ["alert('Only Numerical data allowed')"]. So if they press the 'k' the above message will pop up. Can anyone see how to set this code within this code base
jsfiddle: http://jsfiddle.net/EN8pT/4/
The Code
jquery:
$('input.numberinput').bind('keypress', function (e) {
var w = e.which;
return (w != 8 && w != 0 && (w < 48 || w > 57) && w != 46) ? false : true;
});
​
html
<div class="containercontent">
<div class="label">Enter a number:</div>
<input type="text" name="txtNumber1" id="txtNumber1" value="" class="numberinput" />
<div class="label">Enter a number:</div>
<input type="text" name="txtNumber2" id="txtNumber2" value="" class="numberinput" />
</div>
Simple :
$(document).ready(function () {
$('input.numberinput').bind('keypress', function (e) {
if((e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46) )
{
alert('Only Numbers');
return false;
}
else{
return true;
}
});
});
Link : http://jsfiddle.net/justmelat/EN8pT/
Hello again :) I can help you out with this as well:
$(document).ready(function () {
$('input.numberinput').bind('keypress', function (e) {
var allow = (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46) ? false : true;
if (!allow) {
alert('Only Numerical data allowed');
}
return allow;
});
});?
JSFiddle: http://jsfiddle.net/EN8pT/3/
Enjoy and good luck!

Allow only numeric value in textbox using Javascript

I want to allow only numeric values to be entered into the text and if user enters alphabetic character it should warn the user.
Any suggestion for optimized and short javascript code?
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
from here
use following code
function numericFilter(txb) {
txb.value = txb.value.replace(/[^\0-9]/ig, "");
}
call it in on key up
<input type="text" onKeyUp="numericFilter(this);" />
Here is a solution which blocks all non numeric input from being entered into the text-field.
html
<input type="text" id="numbersOnly" />
javascript
var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
var k = e.which;
/* numeric inputs can come from the keypad or the numeric row at the top */
if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
e.preventDefault();
return false;
}
};​
Please note that, you should allow "system" key as well
$(element).keydown(function (e) {
var code = (e.keyCode ? e.keyCode : e.which), value;
if (isSysKey(code) || code === 8 || code === 46) {
return true;
}
if (e.shiftKey || e.altKey || e.ctrlKey) {
return ;
}
if (code >= 48 && code <= 57) {
return true;
}
if (code >= 96 && code <= 105) {
return true;
}
return false;
});
function isSysKey(code) {
if (code === 40 || code === 38 ||
code === 13 || code === 39 || code === 27 ||
code === 35 ||
code === 36 || code === 37 || code === 38 ||
code === 16 || code === 17 || code === 18 ||
code === 20 || code === 37 || code === 9 ||
(code >= 112 && code <= 123)) {
return true;
}
return false;
}
// Solution to enter only numeric value in text box
$('#num_of_emp').keyup(function () {
this.value = this.value.replace(/[^0-9.]/g,'');
});
for an input box such as :
<input type='text' name='number_of_employee' id='num_of_emp' />
#Shane, you could code break anytime, any user could press and hold any text key like (hhhhhhhhh) and your could should allow to leave that value intact.
For safer side, use this:
$("#testInput").keypress(function(event){
instead of:
$("#testInput").keyup(function(event){
I hope this will help for someone.
or
function isNumber(n){
return (parseFloat(n) == n);
}
http://jsfiddle.net/Vj2Kk/2/
This code uses the event object's .keyCode property to check the characters typed into a given field. If the key pressed is a number, do nothing; otherwise, if it's a letter, alert "Error". If it is neither of these things, it returns false.
HTML:
<form>
<input type="text" id="txt" />
</form>
JS:
(function(a) {
a.onkeypress = function(e) {
if (e.keyCode >= 49 && e.keyCode <= 57) {}
else {
if (e.keyCode >= 97 && e.keyCode <= 122) {
alert('Error');
// return false;
} else return false;
}
};
})($('txt'));
function $(id) {
return document.getElementById(id);
}
For a result: http://jsfiddle.net/uUc22/
Mind you that the .keyCode result for .onkeypress, .onkeydown, and .onkeyup differ from each other.
Javascript For only numeric value in textbox ::
<input type="text" id="textBox" runat="server" class="form-control" onkeydown="return onlyNos(event)" tabindex="0" />
<!--Only Numeric value in Textbox Script -->
<script type="text/javascript">
function onlyNos(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
catch (err) {
alert(err.Description);
}
}
</script>
<!--Only Numeric value in Textbox Script -->

jquery only allow input float number

i'm making some input mask that allows only float number. But current problem is I can't check if multiple dots entered. Can you check those dots and prevent it for me?
Live Code: http://jsfiddle.net/thisizmonster/VRa6n/
$('.number').keypress(function(event) {
if (event.which != 46 && (event.which < 47 || event.which > 59))
{
event.preventDefault();
if ((event.which == 46) && ($(this).indexOf('.') != -1)) {
event.preventDefault();
}
}
});
You can check for the period in the same statement.
Also, you need to use the val method to get the value of the element.
Also, you want to check for the interval 48 to 57, not 47 to 59, otherwise you will also allow /, : and ;.
jQuery(document).ready(function() {
$('.float-number').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
Enter Number:
<input type="text" name="number" value="" class="float-number">
</body>
</html>
I think you guys have missed the left right arrows, delete and backspace keys.
$('.number').keypress(function(event) {
if(event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46)
return true;
else if((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
event.preventDefault();
});
I think everybody forgot the case of pasting text with the mouse, in which you can't detect the keystrokes, because there's none. Here's another approach I have been working on.
// only integer or float numbers (with precision limit)
// example element: <input type="text" value="" class="number" name="number" id="number" placeholder="enter number" />
$('.number').on('keydown keypress keyup paste input', function () {
// allows 123. or .123 which are fine for entering on a MySQL decimal() or float() field
// if more than one dot is detected then erase (or slice) the string till we detect just one dot
// this is likely the case of a paste with the right click mouse button and then a paste (probably others too), the other situations are handled with keydown, keypress, keyup, etc
while ( ($(this).val().split(".").length - 1) > 1 ) {
$(this).val($(this).val().slice(0, -1));
if ( ($(this).val().split(".").length - 1) > 1 ) {
continue;
} else {
return false;
}
}
// replace any character that's not a digit or a dot
$(this).val($(this).val().replace(/[^0-9.]/g, ''));
// now cut the string with the allowed number for the integer and float parts
// integer part controlled with the int_num_allow variable
// float (or decimal) part controlled with the float_num_allow variable
var int_num_allow = 3;
var float_num_allow = 1;
var iof = $(this).val().indexOf(".");
if ( iof != -1 ) {
// this case is a mouse paste (probably also other events) with more numbers before the dot than is allowed
// the number can't be "sanitized" because we can't "cut" the integer part, so we just empty the element and optionally change the placeholder attribute to something meaningful
if ( $(this).val().substring(0, iof).length > int_num_allow ) {
$(this).val('');
// you can remove the placeholder modification if you like
$(this).attr('placeholder', 'invalid number');
}
// cut the decimal part
$(this).val($(this).val().substring(0, iof + float_num_allow + 1));
} else {
$(this).val($(this).val().substring(0, int_num_allow));
}
return true;
});
Good for integer and float values. Plus, copy/paste clipboard event.
var el = $('input[name="numeric"]');
el.prop("autocomplete",false); // remove autocomplete (optional)
el.on('keydown',function(e){
var allowedKeyCodesArr = [9,96,97,98,99,100,101,102,103,104,105,48,49,50,51,52,53,54,55,56,57,8,37,39,109,189,46,110,190]; // allowed keys
if($.inArray(e.keyCode,allowedKeyCodesArr) === -1 && (e.keyCode != 17 && e.keyCode != 86)){ // if event key is not in array and its not Ctrl+V (paste) return false;
e.preventDefault();
} else if($.trim($(this).val()).indexOf('.') > -1 && $.inArray(e.keyCode,[110,190]) != -1){ // if float decimal exists and key is not backspace return fasle;
e.preventDefault();
} else {
return true;
};
}).on('paste',function(e){ // on paste
var pastedTxt = e.originalEvent.clipboardData.getData('Text').replace(/[^0-9.]/g, ''); // get event text and filter out letter characters
if($.isNumeric(pastedTxt)){ // if filtered value is numeric
e.originalEvent.target.value = pastedTxt;
e.preventDefault();
} else { // else
e.originalEvent.target.value = ""; // replace input with blank (optional)
e.preventDefault(); // retur false
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="numeric" value="" placeholder="insert value">
[2017-10-31] Vanilla.js
let el = document.querySelector('input[name="numeric"]');
el.addEventListener('keypress',(event) => {
let k = event.key,
t = isNaN(k),
sc = ['Backspace'].indexOf(k) === -1,
d = k === '.',dV = el.value.indexOf('.') > -1,
m = k === '-',mV = el.value.length > 0;
if((t && sc) && ((d && dV) || (m && dV) || (m && mV) || ((t && !d) && (t && !m)))){event.preventDefault();}
},false);
el.addEventListener('paste',(event) => {
if(event.clipboardData.types.indexOf('text/html') > -1){
if(isNaN(event.clipboardData.getData('text'))){event.preventDefault();}
}
},false);
<input type="text" name="numeric">
Your code seems quite fine but overcomplicated.
First, it is $(this).val().indexOf, because you want to do something with the value.
Second, the event.which == 46 check is inside an if clause that's only passed when event.which != 46, which can never be true.
I ended up with this which works: http://jsfiddle.net/VRa6n/3/.
$('.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
});
I found this way to do this,
$.validator.addMethod("currency", function (value, element) {
return this.optional(element) || /^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/.test(value);
}, "Please specify a valid amount");
https://gist.github.com/jonkemp/9094324
HTML
<input type="text" onkeypress="return isFloatNumber(this,event)" />
Javascript
function isFloatNumber(item,evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode==46)
{
var regex = new RegExp(/\./g)
var count = $(item).val().match(regex).length;
if (count > 1)
{
return false;
}
}
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
jsfiddle.net
Using JQuery.
$(document).ready(function()
{
//Only number and one dot
function onlyDecimal(element, decimals)
{
$(element).keypress(function(event)
{
num = $(this).val() ;
num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
{
event.preventDefault();
}
if($(this).val() == parseFloat(num).toFixed(decimals))
{
event.preventDefault();
}
});
}
onlyDecimal("#TextBox1", 3) ;
});
One-more plugin, based on Carlos Castillo answer
https://github.com/nikita-vanyasin/jquery.numberfield.js
Adds method to jQuery object:
$('input.my_number_field').numberField(options);
where options is (you can pass any or no options):
{
ints: 2, // digits count to the left from separator
floats: 6, // digits count to the right from separator
separator: "."
}
Using jQuery and allowing negative floats :
// Force floats in '.js_floats_only' inputs
$(document).ready(function() {
$('.js_floats_only').each(function() {
// Store starting value in data-value attribute.
$(this).data('value', this.value);
});
});
$(document).on('keyup', '.js_floats_only', function() {
var val = this.value;
if ( val == '-' ) {
// Allow starting with '-' symbol.
return;
} else {
if ( isNaN(val) ) {
// If value is not a number put back previous valid value.
this.value = $(this).data('value');
} else {
// Value is valid, store it inside data-value attribute.
$(this).data('value', val);
}
}
});
For simple cases and without hardcoding some html instructions would fit that pretty enough
<input type="number" step="0.01"/>
$('.number').keypress(function(event){
if($.browser.mozilla == true){
if (event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 9 || event.keyCode == 16 || event.keyCode == 46){
return true;
}
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
This works in all browsers.
<input type="text" data-textboxtype="numeric" />
<script>
$(document).on('keydown', '[data-textboxtype="numeric"]', function (e) {
// Allow: backspace, delete, tab, escape, enter and . and -
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190, 109, 189]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return true;
}
// 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();
return false;
}
return true;
});
</script>
Below Code I am allowing only Digits and Dot symbol.
ASCII characters number starts in 47 and ends with 58 and dot value is 190.
$("#Experince").keyup(function (event) {
debugger
if ((event.which > 47
&& event.which < 58) ||event.which== 190) {
if ($("#Experince").val().length > 3) {
}
} // prevent if not number/dot
else {
$("#Experince").val($("#Experince").val().slice(0, -1))
}
});

Categories