javascript changing the value of a keyboard key - javascript

I have a textfield takes only letters, I want if I pressed (a) I get (b) and if I pressed (b) get (c)...etc, if I pressed (z) get alert("there is no letters after")
<input type="number" id="example" onkeypress="return numbersKey(event)">
<p id="demo"></p>
<input type="text" id="example2" onkeypress="return lettersOnly(event)">
<script>
var myinput = document.getElementById('example'),
myp = document.getElementById('demo');
function numbersKey(evt) {
// Only ASCII charactar in that range allowed
var ASCIICode = event.keyCode;
if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
return false;
return true;
};
}
function lettersOnly()
{
// Only ASCII character in that range allowed
var charCode = event.keyCode;
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8){
return String.fromCharCode(event.keyCode + 1);
}
else
return false;
}

Paste this complete code and run it once to see.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="example2" onkeypress="lettersOnly(event)">
<p id="demo"></p>
</body>
<script>
function lettersOnly(event) {
var charCode = event.keyCode;
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8){
if(charCode == 90 || charCode == 122){
document.getElementById('demo').innerHTML = "There's no letter after";
}
else{
document.getElementById('demo').innerHTML = String.fromCharCode(event.keyCode + 1);
}
}
else{
document.getElementById('demo').innerHTML = "Not Letter";
}
}
</script>
</html>

Related

why i am not getting output when i am using number var in Eclipse in build browser.?

I am using following code in my-eclipse IDE.
<html>
<head>
<script>
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
return true;
}
}
</script>
</head>
<body>
<input name="form_number" onkeypress="return isNumberKey(event)" type="text" maxlength="4">
</body>
</html>
This code does not return the proper output when testing on my built-in browser in my IDE.
I tried to run this snippet on IE (thus using an external browser) and everything seems to work just fine. I feel like there are not mistakes on my code, but I might be wrong. Is my code wrong or is this issue browser related ?
Use parenthesis and try
if (charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
else{
return true;
}
You can try below code snippet. it's same as Click
<script type="text/javascript">
function myKeyPress(e){
var keynum;
if(window.event) { // IE
keynum = e.keyCode;
} else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
if (keynum > 31 && (keynum < 48 || keynum > 57))
return false;
return true;
}
</script>
<form>
<input type="text" onkeypress="return myKeyPress(event)" />
</form>

Backspace is not working in Textarea of My Form on Mozila browser

function onlyAlphabets(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
$('input.facebookUrl').keyup(function(){
if (
($(this).val().length > 0) && ($(this).val().substr(0,24) != 'http://www.facebook.com/')
|| ($(this).val() == '')
){
$(this).val('http://www.facebook.com/');
}
});
<table align="center">
<tr>
<td>
<input name="firstname" class="text_area" maxlength=20 placeholder="Name" type="text" onKeyPress="return onlyAlphabets(event,this)" required id="ValidName" value="" />
</td>
<tr>
<td>
<input type="text" onkeypress="return isNumber(event)" id="volpincode" maxlength=7 name="pincode" value="" required placeholder="Pincode" class="text_area">
</td>
<td><input style="width:300px" type="text" onkeypress="return keyup(event)" class="facebookUrl" name="facebook" value="http://www.facebook.com/$facebook"></td>
<td>
<input style="width:30px" disabled="disabled" type="text" name="facebook" value="+91" />
</td>
</tr>
</tr>
</table>
I am trying to validate the Name and Pin code, as such that in the NAME field only the alphabets have to enter not any other characters and In Pincode only numbers should enter. The form is working in Google chrome as fine, but firefox when i enter and try to delete the text in text field, the characters are not getting deleted.
To validate only alphabets for Name use below code:
$(document).on("keydown", "#NametextboxID", 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) || (key == 9))) {
e.preventDefault();
}
}
});
To validate only numbers for Pin use below code:
$(document).on("keydown", "#PinId", function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) { // if shift, ctrl or alt keys held down
e.preventDefault(); // Prevent character input
} else {
var n = e.keyCode;
if (!((n == 8) // backspace
|| (n == 46) // delete
|| (n >= 35 && n <= 40) // arrow keys/home/end
|| (n >= 48 && n <= 57) // numbers on keyboard
|| (n >= 96 && n <= 105)
|| (n == 9)) // number on keypad
) {
e.preventDefault();
// alert("in if");
// Prevent character input
}
}
});
Add one more condition to the "onlyAlphabets function" for the name field.
if (charCode == 8 || (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
JS Fiddle Link

allowing only alphabets in text box using java script

I want to allow only alphabets in textbox using JavaScript
I used the code:
var nam=f.nm.value;
if(!isNaN(nam))
region.innerHTML="alphabets only";
It is not working and allows numbers as well. How can i fix this?
<html>
<head>
<title>allwon only alphabets in textbox using JavaScript</title>
<script language="Javascript" type="text/javascript">
function onlyAlphabets(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}
</script>
</head>
<body>
<table align="center">
<tr>
<td>
<input type="text" onkeypress="return onlyAlphabets(event,this);" />
</td>
</tr>
</table>
</body>
</html>
just use onkeypress event like below:
<input type="text" name="onlyalphabet" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
From kosare comments, i have create an demo http://jsbin.com/aTUMeMAV/2/
HTML
<form name="f" onsubmit="return onlyAlphabets()">
<input type="text" name="nm">
<div id="notification"></div>
<input type="submit">
</form>
javascript
function onlyAlphabets() {
var regex = /^[a-zA-Z]*$/;
if (regex.test(document.f.nm.value)) {
//document.getElementById("notification").innerHTML = "Watching.. Everything is Alphabet now";
return true;
} else {
document.getElementById("notification").innerHTML = "Alphabets Only";
return false;
}
}
You can use HTML5 pattern attribute to do this:
<form>
<input type='text' pattern='[A-Za-z\\s]*'/>
</form>
If the user enters an input that conflicts with the pattern, it will show an error dialogue automatically.
You can try:
function onlyAlphabets(e, t) {
return (e.charCode > 64 && e.charCode < 91) || (e.charCode > 96 && e.charCode < 123) || e.charCode == 32;
}
:::::HTML:::::
<input type="text" onkeypress="return lettersValidate(event)" />
Only letters no spaces
::::JS::::::::
// ===================== Allow - Only Letters ===============================================================
function lettersValidate(key) {
var keycode = (key.which) ? key.which : key.keyCode;
if ((keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123))
{
return true;
}
else
{
return false;
}
}

JavaScript keycode allow number and plus symbol only

I have this JavaScript function that is used to force user only type number in the textbox. Right now and I want to modify this function so it will allow the user to enter plus (+) symbol. How to achieve this?
//To only enable digit in the user input
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Since the '+' symbol's decimal ASCII code is 43, you can add it to your condition.
for example :
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 43 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
This way, the Plus symbol is allowed.
This code might work. I added support for SHIFT + (equal sign) and the numpad +.
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
var shiftPressed = (window.Event) ? e.modifiers & Event.SHIFT_MASK : e.shiftKey;
if ((shiftPressed && charCode == 187) || (charCode == 107))
{
return true;
} else if ((charCode > 95) && (charCode < 106)) {
return true;
} else if (charCode > 31 && (charCode < 48 || charCode > 57))) {
return false;
} else {
return true;
}
}
this is stupid ... not really an answer at all. I would suggest you to do following.
function isNumberKey(evt)
{
console.log(evt.keyCode);
return false;
}
And find out the ranges of all keys, and implement it.
It's Work. Javascript keycode allow number and plus symbol only
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation</title>
</head>
<body>
<form name="form1" action="#">
Mobile Number: <input type='text' id='PhoneNumber' maxlength="10" onKeyPress="return IsNumeric3(event);" ondrop="return false;" onpaste="return false;"/>
<span id="error3" style="color: Red; display: none">* Input digits (0 - 9)</span>
</form>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8);
specialKeys.push(43);
specialKeys.push(37);
specialKeys.push(39);
//Backspace
function IsNumeric3(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = (keyCode != 37 && keyCode != 8 && keyCode != 46 && (keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error3").style.display = ret ? "none" : "inline";
return ret;
}
</script>
<script>
function stringlength(inputtxt, minlength, maxlength)
{
var field = inputtxt.value;
var mnlen = minlength;
var mxlen = maxlength;
if(field.length<mnlen || field.length> mxlen)
{
alert("Please input the 10 digit mobile number");
return false;
}
else
{
return true;
}
}
</script>
</body>
</html>
Thank you friends
Here is the modified code:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if ( (charCode >= 48 && charCode <= 57) || charCode == 43)
return true;
return false;
}
Here is the code . working fine with numbers and plus + sign in phone fields. you will have to implement the code on keydown function . target the id/class of the particular phone field and use keydown function.
//allows only these keys
// backspace, delete, tab, escape, and enter
if ( event.keyCode == 107 || event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
return;
}
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 )) {
event.preventDefault();
}
}
Using experience of my colleagues above, write one function, that fits me well. It filters all except numbers, arrows and backspace. Maybe it would be useful for somebody.
function isKeyCorrect(keyEvent) {
var charCode = keyEvent.which ? keyEvent.which : keyEvent.keyCode;
var isNotNumber = charCode < 48 || charCode > 57;
var isNotArrow = charCode < 37 || charCode > 40;
var isNotBackspace = charCode !== 8;
return isNotNumber && isNotArrow && isNotBackspace;
}
<script type="text/javascript">
$(document).ready(function() {
`enter code here` $('#form-1').submit(function(msg) {
$.post("action.php?act=login",$(this).serialize(),function(data){
if (data == 'ERR:A3001004') { alert("Güvenlik hatası, sayfayı yenileyin."); }
else if (data == 'TIMEEND') { alert("Anahtarınızın süresi dolmuş."); }
else if (data == 'INVALID') { alert("Geçersiz anahtar şifresi girdiniz."); }
else if (data == 'OK') { alert("Başarıyla giriş yaptınız. Yetişkinlere göre içerik barındıran sitelere erişim sağlayabilirsiniz."); }
});
return false;
});
});
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>

Restricting input to textbox: allowing only numbers and decimal point

How can I restrict input to a text-box so that it accepts only numbers and the decimal point?
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return isNumberKey(event)"
type="text" name="txtChar">
</BODY>
</HTML>
This really works!
The accepted solution is not complete, since you can enter multiple '.', for example 24....22..22. with some small modifications it will work as intended:
<html>
<head>
<script type="text/javascript">
function isNumberKey(txt, evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 46) {
//Check if the text already contains the . character
if (txt.value.indexOf('.') === -1) {
return true;
} else {
return false;
}
} else {
if (charCode > 31 &&
(charCode < 48 || charCode > 57))
return false;
}
return true;
}
</script>
</head>
<body>
<input type="text" onkeypress="return isNumberKey(this, event);" />
</body>
</html>
form.onsubmit = function(){
return textarea.value.match(/^\d+(\.\d+)?$/);
}
Is this what you're looking for?
I hope it helps.
EDIT: I edited my example above so that there can only be one period, preceded by at least one digit and followed by at least one digit.
Here is one more solution which allows for decimal numbers and also limits the digits after decimal to 2 decimal places.
function isNumberKey(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8))
return false;
else {
var len = $(element).val().length;
var index = $(element).val().indexOf('.');
if (index > 0 && charCode == 46) {
return false;
}
if (index > 0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 3) {
return false;
}
}
}
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="rate" placeholder="Billing Rate" required onkeypress="return isNumberKey(event,this)">
All solutions presented here are using single key events. This is very error prone since input can be also given using copy'n'paste or drag'n'drop. Also some of the solutions restrict the usage of non-character keys like ctrl+c, Pos1 etc.
I suggest rather than checking every key press you check whether the result is valid in respect to your expectations.
var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = document.getElementById("test1").value;
function validateNumber(elem) {
if (validNumber.test(elem.value)) {
lastValid = elem.value;
} else {
elem.value = lastValid;
}
}
<textarea id="test1" oninput="validateNumber(this);" ></textarea>
The oninput event is triggered just after something was changed in the text area and before being rendered.
You can extend the RegEx to whatever number format you want to accept. This is far more maintainable and extendible than checking for single key presses.
Are you looking for something like this?
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
</BODY>
</HTML>
Just need to apply this method in Jquery and you can validate your textbox to just accept number with a decimal only.
function IsFloatOnly(element) {
var value = $(element).val();
var regExp ="^\\d+(\\.\\d+)?$";
return value.match(regExp);
}
Please see working demo here
here is script that cas help you :
<script type="text/javascript">
// price text-box allow numeric and allow 2 decimal points only
function extractNumber(obj, decimalPlaces, allowNegative)
{
var temp = obj.value;
// avoid changing things if already formatted correctly
var reg0Str = '[0-9]*';
if (decimalPlaces > 0) {
reg0Str += '\[\,\.]?[0-9]{0,' + decimalPlaces + '}';
} else if (decimalPlaces < 0) {
reg0Str += '\[\,\.]?[0-9]*';
}
reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
reg0Str = reg0Str + '$';
var reg0 = new RegExp(reg0Str);
if (reg0.test(temp)) return true;
// first replace all non numbers
var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (decimalPlaces != 0 ? ',' : '') + (allowNegative ? '-' : '') + ']';
var reg1 = new RegExp(reg1Str, 'g');
temp = temp.replace(reg1, '');
if (allowNegative) {
// replace extra negative
var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
var reg2 = /-/g;
temp = temp.replace(reg2, '');
if (hasNegative) temp = '-' + temp;
}
if (decimalPlaces != 0) {
var reg3 = /[\,\.]/g;
var reg3Array = reg3.exec(temp);
if (reg3Array != null) {
// keep only first occurrence of .
// and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
reg3Right = reg3Right.replace(reg3, '');
reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
}
}
obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
var key;
var isCtrl = false;
var keychar;
var reg;
if(window.event) {
key = e.keyCode;
isCtrl = window.event.ctrlKey
}
else if(e.which) {
key = e.which;
isCtrl = e.ctrlKey;
}
if (isNaN(key)) return true;
keychar = String.fromCharCode(key);
// check for backspace or delete, or if Ctrl was pressed
if (key == 8 || isCtrl)
{
return true;
}
reg = /\d/;
var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
var isFirstC = allowDecimal ? keychar == ',' && obj.value.indexOf(',') == -1 : false;
return isFirstN || isFirstD || isFirstC || reg.test(keychar);
}
function blockInvalid(obj)
{
var temp=obj.value;
if(temp=="-")
{
temp="";
}
if (temp.indexOf(".")==temp.length-1 && temp.indexOf(".")!=-1)
{
temp=temp+"00";
}
if (temp.indexOf(".")==0)
{
temp="0"+temp;
}
if (temp.indexOf(".")==1 && temp.indexOf("-")==0)
{
temp=temp.replace("-","-0") ;
}
if (temp.indexOf(",")==temp.length-1 && temp.indexOf(",")!=-1)
{
temp=temp+"00";
}
if (temp.indexOf(",")==0)
{
temp="0"+temp;
}
if (temp.indexOf(",")==1 && temp.indexOf("-")==0)
{
temp=temp.replace("-","-0") ;
}
temp=temp.replace(",",".") ;
obj.value=temp;
}
// end of price text-box allow numeric and allow 2 decimal points only
</script>
<input type="Text" id="id" value="" onblur="extractNumber(this,2,true);blockInvalid(this);" onkeyup="extractNumber(this,2,true);" onkeypress="return blockNonNumbers(this, event, true, true);">
For anyone stumbling here like I did, here is a jQuery 1.10.2 version I wrote which is working very well for me albeit resource intensive:
/***************************************************
* Only allow numbers and one decimal in text boxes
***************************************************/
$('body').on('keydown keyup keypress change blur focus paste', 'input[type="text"]', function(){
var target = $(this);
var prev_val = target.val();
setTimeout(function(){
var chars = target.val().split("");
var decimal_exist = false;
var remove_char = false;
$.each(chars, function(key, value){
switch(value){
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
if(value === '.'){
if(decimal_exist === false){
decimal_exist = true;
}
else{
remove_char = true;
chars[''+key+''] = '';
}
}
break;
default:
remove_char = true;
chars[''+key+''] = '';
break;
}
});
if(prev_val != target.val() && remove_char === true){
target.val(chars.join(''))
}
}, 0);
});
A small correction to #rebisco's brilliant answer to validate the decimal perfectly.
function isNumberKey(evt) {
debugger;
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 46 && evt.srcElement.value.split('.').length>1) {
return false;
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
If you want it for float values,
Here is the function I am using
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function check(e, value) {
//Check Charater
var unicode = e.charCode ? e.charCode : e.keyCode;
if (value.indexOf(".") != -1)
if (unicode == 46) return false;
if (unicode != 8)
if ((unicode < 48 || unicode > 57) && unicode != 46) return false;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return check(event,value)" type="text" name="txtChar">
</BODY>
</HTML>
function onlyDotsAndNumbers(txt, event) {
var charCode = (event.which) ? event.which : event.keyCode
if (charCode == 46) {
if (txt.value.indexOf(".") < 0)
return true;
else
return false;
}
if (txt.value.indexOf(".") > 0) {
var txtlen = txt.value.length;
var dotpos = txt.value.indexOf(".");
//Change the number here to allow more decimal points than 2
if ((txtlen - dotpos) > 2)
return false;
}
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input type="text" id="txtAmount" onkeypress="return onlyDotsAndNumbers(this,event);" maxlength="10" oncopy="return false" ondrag="return false" ondrop="return false" onpaste="return false" />
Only Numbers, One decimal point, No Copy Paste.
inputelement.onchange= inputelement.onkeyup= function isnumber(e){
e= window.event? e.srcElement: e.target;
while(e.value && parseFloat(e.value)+''!= e.value){
e.value= e.value.slice(0, -1);
}
}
function integerwithdot(s, iid){
var i;
s = s.toString();
for (i = 0; i < s.length; i++){
var c;
if (s.charAt(i) == ".") {
} else {
c = s.charAt(i);
}
if (isNaN(c)) {
c = "";
for(i=0;i<s.length-1;i++){
c += s.charAt(i);
}
document.getElementById(iid).value = c;
return false;
}
}
return true;
}
Suppose your textbox field name is Income
Call this validate method when you need to validate your field:
function validate() {
var currency = document.getElementById("Income").value;
var pattern = /^[1-9]\d*(?:\.\d{0,2})?$/ ;
if (pattern.test(currency)) {
alert("Currency is in valid format");
return true;
}
alert("Currency is not in valid format!Enter in 00.00 format");
return false;
}
Extending the #rebisco's answer. this below code will allow only numbers and single '.'(period) in the text box.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
} else {
// If the number field already has . then don't allow to enter . again.
if (evt.target.value.search(/\./) > -1 && charCode == 46) {
return false;
}
return true;
}
}
alternative way to restrict input to a text-box so that it accepts only numbers and the decimal point is to
use javascript inside the html input. This works for me:
<input type="text" class="form-control" id="price" name="price" placeholder="Price"
vrequired onkeyup="this.value=this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')">
--Accepts--
9
9.99
--Do not accept--
9.99.99
ABC
Better solution
var checkfloats = function(event){
var charCode = (event.which) ? event.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
if(event.target.value.indexOf('.') >=0 && charCode == 46)
return false;
return true;
}
I chose to tackle this on the oninput event in order to handle the issue for keyboard pasting, mouse pasting and key strokes. Pass true or false to indicate decimal or integer validation.
It's basically three steps in three one liners. If you don't want to truncate the decimals comment the third step. Adjustments for rounding can be made in the third step as well.
// Example Decimal usage;
// <input type="text" oninput="ValidateNumber(this, true);" />
// Example Integer usage:
// <input type="text" oninput="ValidateNumber(this, false);" />
function ValidateNumber(elm, isDecimal) {
try {
// For integers, replace everything except for numbers with blanks.
if (!isDecimal)
elm.value = elm.value.replace(/[^0-9]/g, '');
else {
// 1. For decimals, replace everything except for numbers and periods with blanks.
// 2. Then we'll remove all leading ocurrences (duplicate) periods
// 3. Then we'll chop off anything after two decimal places.
// 1. replace everything except for numbers and periods with blanks.
elm.value = elm.value.replace(/[^0-9.]/g, '');
//2. remove all leading ocurrences (duplicate) periods
elm.value = elm.value.replace(/\.(?=.*\.)/g, '');
// 3. chop off anything after two decimal places.
// In comparison to lengh, our index is behind one count, then we add two for our decimal places.
var decimalIndex = elm.value.indexOf('.');
if (decimalIndex != -1) { elm.value = elm.value.substr(0, decimalIndex + 3); }
}
}
catch (err) {
alert("ValidateNumber " + err);
}
}
Starting from #rebisco answer :
function count_appearance(mainStr, searchFor) {
return (mainStr.split(searchFor).length - 1);
}
function isNumberKey(evt)
{
$return = true;
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
$return = false;
$val = $(evt.originalTarget).val();
if (charCode == 46) {
if (count_appearance($val, '.') > 0) {
$return = false;
}
if ($val.length == 0) {
$return = false;
}
}
return $return;
}
Allows only this format : 123123123[.121213]
Demo here demo
Hope it will work for you.
<input type="text" onkeypress="return chkNumeric(event)" />
<script>
function chkNumeric(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
if (charCode == 46) { return true; }
else { return false; }
}
return true;
}
</script>
Following code worked for me
The input box with "onkeypress" event as follows
<input type="text" onkeypress="return isNumberKey(this,event);" />
The function "isNumberKey" is as follows
function isNumberKey(txt, evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 46) {
//Check if the text already contains the . character
if (txt.value.indexOf('.') === -1) {
return true;
} else {
return false;
}
} else {
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
}
return true;
}
I observed that for all the answers provided here, the things are not working if we select some portion of the text in textbox and try to overwrite that part.
So I modified the function which is as below:
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
if (charCode == 46 && evt.srcElement.value.split('.').length>1 )
{
return false;
}
if(evt.srcElement.selectionStart<evt.srcElement.selectionEnd)
{
return true;
}
if(evt.srcElement.value.split('.').length>1 && evt.srcElement.value.split('.')[1].length==2)
{
return false;
}
return true;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return isNumberKey(event)"
type="text" name="txtChar">
</BODY>
</HTML>
For Decimal numbers and also allowing Negatives numbers with 2 places for decimals after the point... I modified the function to:
<input type="text" id="txtSample" onkeypress="return isNumberKey(event,this)"/>
function isNumberKey(evt, element){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8 || charCode == 45))
return false;
else {
var len = $(element).val().length;
// Validation Point
var index = $(element).val().indexOf('.');
if ((index > 0 && charCode == 46) || len == 0 && charCode == 46) {
return false;
}
if (index > 0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 3) {
return false;
}
}
// Validating Negative sign
index = $(element).val().indexOf('-');
if ((index > 0 && charCode == 45) || (len > 0 && charCode == 45)) {
return false;
}
}
return true;
}
<input type="text" class="number_only" />
<script>
$(document).ready(function() {
$('.number_only').keypress(function (event) {
return isNumber(event, this)
});
});
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if ((charCode != 45 || $(element).val().indexOf('-') != -1) && (charCode != 46 || $(element).val().indexOf('.') != -1) && ((charCode < 48 && charCode != 8) || charCode > 57)){
return false;
}
else {
return true;
}
}
</script>
http://www.encodedna.com/2013/05/enter-only-numbers-using-jquery.htm
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if(charCode==8 || charCode==13|| charCode==99|| charCode==118 || charCode==46)
{
return true;
}
if (charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
return true;
}
It will allow only numeric and will let you put "." for decimal.
<script type="text/javascript">
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
#Html.EditorFor(model => model.Orderids, new { id = "Orderids", Onkeypress=isNumberKey(event)})
This works fine.
Best and working solution with Pure-Javascript sample
Live demo : https://jsfiddle.net/manoj2010/ygkpa89o/
<script>
function removeCommas(nStr) {
if (nStr == null || nStr == "")
return "";
return nStr.toString().replace(/,/g, "");
}
function NumbersOnly(myfield, e, dec,neg)
{
if (isNaN(removeCommas(myfield.value)) && myfield.value != "-") {
return false;
}
var allowNegativeNumber = neg || false;
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
var srcEl = e.srcElement ? e.srcElement : e.target;
// control keys
if ((key == null) || (key == 0) || (key == 8) ||
(key == 9) || (key == 13) || (key == 27))
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// decimal point jump
else if (dec && (keychar == ".")) {
//myfield.form.elements[dec].focus();
return srcEl.value.indexOf(".") == -1;
}
//allow negative numbers
else if (allowNegativeNumber && (keychar == "-")) {
return (srcEl.value.length == 0 || srcEl.value == "0.00")
}
else
return false;
}
</script>
<input name="txtDiscountSum" type="text" onKeyPress="return NumbersOnly(this, event,true)" />
Working on the issue myself, and that's what I've got so far. This more or less works, but it's impossible to add minus afterwards due to the new value check. Also doesn't allow comma as a thousand separator, only decimal.
It's not perfect, but might give some ideas.
app.directive('isNumber', function () {
return function (scope, elem, attrs) {
elem.bind('keypress', function (evt) {
var keyCode = (evt.which) ? evt.which : event.keyCode;
var testValue = (elem[0].value + String.fromCharCode(keyCode) + "0").replace(/ /g, ""); //check ignores spaces
var regex = /^\-?\d+((\.|\,)\d+)?$/;
var allowedChars = [8,9,13,27,32,37,39,44,45, 46] //control keys and separators
//allows numbers, separators and controll keys and rejects others
if ((keyCode > 47 && keyCode < 58) || allowedChars.indexOf(keyCode) >= 0) {
//test the string with regex, decline if doesn't fit
if (elem[0].value != "" && !regex.test(testValue)) {
event.preventDefault();
return false;
}
return true;
}
event.preventDefault();
return false;
});
};
});
Allows:
11 11 .245 (in controller formatted on blur to 1111.245)
11,44
-123.123
-1 014
0123 (formatted on blur to 123)
doesn't allow:
!##$/*
abc
11.11.1
11,11.1
.42
<input type="text" onkeypress="return isNumberKey(event,this)">
<script>
function isNumberKey(evt, obj) {
var charCode = (evt.which) ? evt.which : event.keyCode
var value = obj.value;
var dotcontains = value.indexOf(".") != -1;
if (dotcontains)
if (charCode == 46) return false;
if (charCode == 46) return true;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>

Categories

Resources