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>
Related
I've a function ,
function validateDigit(event) {
var key = window.event ? event.keyCode : event.which;
if (event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 190) {
return true;
}
else if ( key < 48 || key > 57 ) {
return false;
}else if(event.shiftKey == true){
return false;
}
else return true;
};
which takes only numeric numbers and no alphabets .But Now I Want To Set The First 3 digits of a mobile phone number as like 017/016/015/018 and after then there will be more 8 digits.how to do this ?
Don't.
<form action="javascript:alert('Submitted!');">
<input type="tel" pattern="01[5-8]\d{8}" title="Mobile number beginning with 015/016/017/018" />
</form>
Done.
How to Allow float value in Input.When i am trying to input float value decimal (.) not able to enter.
Example: 143.52, 178.30, 3658.20 etc..
http://jsfiddle.net/vLEZY/75/
<input type="text" onkeypress='return validateQty(event);'>
<script
function validateQty(event) {
var key = window.event ? event.keyCode : event.which;
if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39) {
return true;
} else if (key < 48 || key > 57) {
return false;
} else return true;
};
</script>
Here you go: http://jsfiddle.net/mcg0x0hh/2/
if (event.keyCode == 8 || key == 46 || event.keyCode == 37 || event.keyCode == 39)
I modified event.keyCode in key for the code 46, which is the dot. I would change all event.keyCode to key, unless you have a good reason to keep them like that.
I validate the phone number using below code its working fine but i allow char at first time while user entering the values. how i can solve it. . . .
$('.Number').keypress(function () {
$('.Number').keypress(function (event) {
var keycode;
keycode = event.keyCode ? event.keyCode : event.which;
if (!(event.shiftKey == false && (keycode == 46 || keycode == 8 ||
keycode == 37 ||keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
event.preventDefault();
}
});
});
The first character is unrestricted because you have nested keypress handlers. Try this:
$('.Number').keypress(function (event) {
var keycode = event.which;
if (!(event.shiftKey == false && (keycode == 46 || keycode == 8 || keycode == 37 || keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
event.preventDefault();
}
});
Try
$('.Number').keyup(function (event) {
var keycode = event.which;
if (!(event.shiftKey == false && (keycode == 46 || keycode == 8 || keycode == 37 || keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
event.preventDefault();
}
});
Here is a function that will validate the input. It will return true if the value is a number, false otherwise. Numbers are charcode 48 - 57. This function also allows all control characters to return true. (<32)
function isNumber(evt)
{
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 32 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
Here is a chart of the codes.
<html>
<head>
<title>number validation</title>
<script>
function checkNumber(check)
{
var a = document.getElementById("txt_contact_no").value;
//var x=check.which;
//var x = a.charCode;
var x = a.keyCode;
if(!(a >= 48 || a <= 57))
{
alert("enter only numbers");
return false;
}
else if(a=="" || a==null)
{
alert("field is blank");
return false;
}
// if no is more then the value
/*else if (a.length <= 9)
{
alert("enter minimum 10 characters");
return false;
}*/
alert("done");
return true;
}
</script>
</script>
</head>
<body>
<table>
<form name=form1 method=post action="#">
<tr>
<td>
<b>Subjects</b><input type="text" name="contact_no" id="txt_contact_no" onblur="checkNumber(this)">
</td>
</tr>
<tr>
<td><p id="p1"></p></td>
</tr>
</form>
</table>
</body>
This is the simplest solution for KeyPress Number Events:
$(document).ready(function(){
$(".Number").keypress(function(event){
var keycode = event.which;
if (!(keycode >= 48 && keycode <= 57)) {
event.preventDefault();
}
});
});
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 -->
This question already has answers here:
HTML text input allow only numeric input
(78 answers)
Closed 8 years ago.
<input type="text" id="target" />
How to do it with jQuery?
Though a bit more fragile since it uses keycodes... the following would work more intuitive because it makes it completely impossible to enter non-numbers:
$("#target").keydown(function(event) {
return ( event.keyCode < 32 || // Control characters
( event.keyCode >= 48 && event.keyCode <= 57 ) || // Numbers
event.keyCode == 127 ); // Delete key
});
Note to add: This is actually not the best way to go... since a (windows) ALT+[num]132 will make it possible to enter ä into the box. It should be combined with the keyup event to ensure that no characters have been entered as well like so, Combined:
$("#target").keydown(function(event) {
return ( event.keyCode < 32 || // Control characters
( event.keyCode >= 48 && event.keyCode <= 57 ) || // Numbers
event.keyCode == 127 ); // Delete key
});
$("#target").keyup(function(event) {
event.target.value = event.target.value.replace(/[^0-9]/g, "");
});
Also, this doesn't work with the num-pad-numbers over here so it definately is more fragile than a simple blur() event.
$("#target").blur(function(event) {
event.target.value = event.target.value.replace(/[^0-9]/g, "");
});
This will work as well:
$("#target").keypress(function(event) {
event.target.value = event.target.value.replace(/[^0-9]/g, "");
});
$('input[type=text].someclass').blur(function(event)
{
event.target.value = event.target.value.replace(/[^0-9]/g, "");
});
function onlyNumbers(evt) {
var e = evt;
if(window.event){ // IE
var charCode = e.keyCode;
} else if (e.which) { // Safari 4, Firefox 3.0.4
var charCode = e.which;
}
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Source
if (!$.browser.mozilla) {
if (event.keyCode && (event.keyCode < 48 || event.keyCode > 57))
event.preventDefault();
}
else {
if (event.charCode && (event.charCode < 48 || event.charCode > 57))
event.preventDefault();
}