I am currently building an application and I want a javascript or jquery condition that only allows numbers to be entered into the text box and/or the following percent but i am not sure how to obtain this... I found this but how do i allow the following percent
Asked
Active
Viewed 2,991 times
4
-
Which of the suggestions in that link do you want to use? For most it is just specifying a regex that covers numbers and I assume the % will always come at the end? – mrtsherman Aug 09 '11 at 03:25
4 Answers
5
$(document).ready(function() {
$("#my_input").keypress(function(event) {
// Allow only backspace, delete, and percent sign
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 37) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
});
});

AlienWebguy
- 76,997
- 17
- 122
- 145
-
characters can be copy pasted on the text field ,!! Can you please update the answer...?? – Aju Jan 12 '18 at 11:02
-
@Aju at that point it would be up to you to decide how to handle that - would you reject the entire pasted content or filter out the invalid characters? I wouldn't say there's a "right" answer for your comment. Definitely multiple approaches that work. – AlienWebguy Jan 15 '18 at 19:09
2
try this one,
$(".common").submit(function(){
var inputVal = $('#input').val();
var characterReg = /^[0-9]+%?$/;
if (!characterReg.test(inputVal)) {
alert('in-correct');
}
else
{
alert('correct');
}
return false;
});

Khawer Zeshan
- 9,470
- 6
- 40
- 63
0
Hehe this is what I came up with
if(!parseInt(String.fromCharCode(event.keyCode)))
event.preventDefault();
This should be used in the kepress
jquery event.

KO.
- 173
- 3
- 18
0
Try this. In this you can add what else you want to allow or restrict.
$("textboxSelector").keypress(function(e) {
var key = e.which;
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
return false;
}
});

ShankarSangoli
- 69,612
- 13
- 93
- 124
-
The character will already be displayed by the time a `keyup` event fires. I think he means to use `keypress` – Maverick Aug 09 '11 at 03:33
-
@AlienWebguy - Edited my answer, keyup replaced by keydown, it works now. Thanks anways. – ShankarSangoli Aug 09 '11 at 03:34
-
Removed my downvote. I think Matt is right about keypress though. It's relevant with the shift key. – AlienWebguy Aug 09 '11 at 03:55
-
Yea bro this still doesn't work. I can add `!@#$^&*()` which are not allowed per OP's request. – AlienWebguy Aug 09 '11 at 21:30
-
@AlienWebguy - It was due to keydown event, changed it to keypress. Now it works fine, thank you so much :) – ShankarSangoli Aug 10 '11 at 00:17