4

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

Community
  • 1
  • 1
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321
  • 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 Answers4

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(); 
            }   
        }
    });
});

Demo: http://jsfiddle.net/AlienWebguy/ufqse/

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