I am trying to prevent the user from entering anything but a number. It works in Chrome but not Firefox. I have gone through many solutions but no luck. I have used keydown, keypress, different events etc. Please help. If it helps this is all in a aspx file.
onkeypress="return myFunction(event);"
<script type="text/javascript">
// Check if key press is a number
function myFunction(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
alert("Enter Numbers Only");
return false;
}
return true;
}
</script>
I don't understand this line
var e = event || evt; // for trans-browser compatibility
Where do you get event? This was throwing error in Firefox.
I modified the code and tested it with Chrome and Firefox. First the HTML with input
<input onkeypress="return validate(event);" />
and the function
// Check if key press is a number
function validate(e)
{
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
{
alert("Enter Numbers Only");
return false;
}
return true;
}
http://jsfiddle.net/bskqpgvy/2/
Not sure if part of the script wasn't included, but from what I can see the code provided above didn't work in any browser.
http://jsfiddle.net/e5d8txa2/
window.addEventListener("keypress", function(evt) {
myFunction(evt);
});
// Check if key press is a number
function myFunction(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
alert("Enter Numbers Only");
return false;
}
return true;
}
As an aside, if the field is typed only for numbers, in modern browsers you can use the "number" type in the input field. This should throw an visible error to the user when attempting to submit. Of course, you should also verify the field values in other ways as necessary.
Related
Here I have a function which only allows numeric and percentage. But it is allowing minus(-), I want to restrict that minus in that script. How can I restrict.Here is my script.Or please suggest me a dirctive for this.
function validateQty(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 45 && charCode != 8 && charCode != 37 && (charCode != 46) && (charCode < 48 || charCode > 57))
return false;
if (charCode == 46) {
if ((el.value) && (el.value.indexOf('.') >= 0))
return false;
else
return true;
}
return true;
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = evt.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
};
You can allow what you want to be as input. Do something like this.
function restrictInput(el) {
el.addEventListener('input', function(e) {
if (!e.target.value.match(/^\d+$|%$/)) {
e.target.value = e.target.value.slice(0, -1)
}
console.log(e.target.value);
})
}
restrictInput(document.getElementById("input1"));
restrictInput(document.getElementById("input2"));
<input id="input1">
<input id="input2">
updated: As asked by OP. A generic function to handle inputs.
NOTE: You can add more restrictions as you want inside this function
You could use input=number
<input type="number" min="0" />
Using javascript you could do:
// Select your input element.
var numInput = document.querySelector('input');
// Listen for input event on numInput.
numInput.addEventListener('input', function () {
// Let's match only digits.
var num = this.value.match(/^\d+$/);
if (num === null) {
// If we have no match, value will be empty.
this.value = "";
}
}, false)
If the data from the input field will be sent to the server, make sure to add this validation on the server too.
I think you can simplify your script by just testing it against a regular expression.
So your function would essentially change to something like this
function validateQty(el, evt)
{
var regex = new RegExp(/^\d+$|%$/);
return regex.test(el.value);
};
JSFiddle
On a textbox; there is decimal validation:
i.e User can enter only Numbers(upto two place decimal) and Dot.
Those are on keypress and keyup.
When number is entered directly, it works.
But when we drag and drop some alphabets in textbox
then it does not work; till i click in textbox
What events are provided by Javascript which help me to detect whether values is dragged and dropped to textbox.
Try this:
$(document).ready(function() {
var oldVal = '';
$('.myTexbox').keypress(function (event) {
var a = isDecimalNumber(event, this)
if (this.value.match("^[0-9]*[.,]?[0-9]{0,2}$"))
oldVal = this.value;
return a;
});
$('.myTexbox').keyup(function (event) {
if (!this.value.match("^[0-9]*[.,]?[0-9]{0,2}$")) {
$(this).val(oldVal);
}
});
$('.myTexbox').on("drop", function(event) {
event.preventDefault();
event.stopPropagation();
if (!this.value.match("^[0-9]*[.,]?[0-9]{0,2}$")) {
$(this).val(oldVal);
}
});
});
function isDecimalNumber(eve, element) {
var charCode = (eve.which) ? eve.which : event.keyCode
if (charCode == 44 || charCode == 46 || charCode == 8 || (charCode > 48 && charCode < 57))
return true;
return false;
}
I think this is exactly what you need.
I tested the code in JS Fiddle and it works like expected.
I am working on an old application to make it compatible with firefox. As the old application does not uses Jquery I have to do all my stuffs using Javascript only.
I have a input field for entering date.This field should only allow 0-9 numeric values. So I have modified the code like this for making it compatible with firefox.
var event = window.event || ffEvent ; //ffEvent is the function argument
var intKeyCode = event.keyCode || event.which;
if (intKeyCode < 48 || intKeyCode > 57){
if(event.preventDefault){
event.preventDefault();
}
else{
event.returnValue = false;
}
}
But now the problem is event.returnValue = false allows keys like Backspace,Tab,Delete,Arrow buttons where as event.preventDefault() does not allow these buttons. One must allow these buttons for a input field.
So is there any solutions for firefox which exactly behave same as event.returnValue=false
why not use the keyCodes to check if the character is digit or not
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
var event = window.event || ffEvent ; //ffEvent is the function argument
var intKeyCode = event.keyCode || event.which;
if (intKeyCode > 31 && (intKeyCode < 48 || intKeyCode > 57))
return false;
return true;
}
in the keypress of input field call this event, as
onkeypress="return isNumberKey(event)
All you need to do is skip the event.preventDefault() when the key is one of the keys you want to allow:
window.onload = function () {
document.getElementById('myField').onkeypress = function (event) {
var keyCode = event.keyCode || event.which,
allowedKey = keyCode === 8 || // backspace
keyCode === 9 || // tab
keyCode === 13 || // enter
keyCode === 37 || // left
keyCode === 39 || // right
keyCode === 46 || // del
(keyCode >= 48 && keyCode <= 57);
if (!allowedKey) {
event.preventDefault();
}
};
};
<input type="text" id="myField" />
I'm looking for a solution for a (as it seems) common problem.
I want JavaScript to check a specific format when entering data in a input-field.
This is what I've got:
HTML:
<input onkeypress=" return fieldFormat(event)">
JavaScript:
<script type="text/javascript">
//Checks spelling in realtime, if JavaScript is enabled.
function fieldFormat(event){
var charCode = (window.event) ? window.event.keyCode : event.keyCode;
var parts = event.target.value.split('.');
if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)) || (parts.length > 1 && charCode == 46))
return false;
return true;
}
</script>
This works fine in Chrome and IE. But for some reason, Firefox gives me troubles ^^
Any hints?
Some browsers use keyCode, others use which, so try this:
function fieldFormat(event){
var e = event || window.event,
charCode = e.keyCode || e.which,
parts = e.target.value.split('.');
if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)) || (parts.length > 1 && charCode == 46))
return false;
return true;
}
Check this one - seems like it's common https://support.mozilla.org/pl/questions/998291
I have a function below where it doesn't allow the user to type in letters in a textbox but it keeps saying event is undefined. Where and how am I suppose to define event?
Below is the function:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Below is the html where this could be used:
onkeypress="return isNumberKey(event)"
change
var charCode = (evt.which) ? evt.which : event.keyCode
to
var charCode = (evt.which) ? evt.which : evt.keyCode
or if you are using jQuery (you tagged it but aren't using it) you could do
$('#textareaid').keypress(function(e) {
if (e.which > 31 && (e.which < 48 || e.which > 57)) {
e.preventDefault();
}
});
where your html is
<textarea id="textareaid"></textarea>
See event.preventDefault()
Note on how to get key pressed using jQuery
To determine which character was entered, examine the event object
that is passed to the handler function. While browsers use differing
properties to store this information, jQuery normalizes the .which
property so you can reliably use it to retrieve the character code.
Taken from the .keypress() docs
here is the code which should work:
function checkerFunction(e){
var charCode=e.which || e.keyCode;
if(charCode<=31 || charCode>=48 && charCode<=57)return true;
return false;
}
and the event binding should be
onkeypress="return checkerFunction(window.event)"
For the record I think that most of the answers above don't take into consideration the ARROW keys.
This should be how it works incase you are googling this.
function isNumberKey(event)
{
var charCode = event.charCode;
if ((charCode < 48 || charCode > 57) && charCode != 0){
return false;
}
return true;
}