最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do i only allow a text box to only have numbers and the following percent symbol? - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question edited May 23, 2017 at 12:04 CommunityBot 11 silver badge asked Aug 9, 2011 at 3:12 Matt ElhotibyMatt Elhotiby 44.1k91 gold badges224 silver badges328 bronze badges 1
  • 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 e at the end? – mrtsherman Commented Aug 9, 2011 at 3:25
Add a ment  | 

4 Answers 4

Reset to default 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/AlienWebguy/ufqse/

try this one,

    $(".mon").submit(function(){
    var inputVal = $('#input').val();
    var characterReg = /^[0-9]+%?$/;
    if (!characterReg.test(inputVal)) {
        alert('in-correct');
    }
    else
    {
        alert('correct');
    }
        return false;
    });

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

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论