Accept only positive number using Jquery

December 20th, 2008

Có thể sử dụng Event Handling hoặc Event Helper. Tất nhiên là sử dụng Event Helper thì ngắn hơn rồi :)

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
//when key is pressed in the textbox
$("#quantity").keypress(function (e)
{
  //if the letter is not digit then display error and don't type anything
  if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
  {
    //display error message
    $("#errmsg").html("Digits Only").show().fadeOut("slow");
    return false;
  }
});

Mình quen viết thế này hơn:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
//when key is pressed in the textbox
$("#quantity").keypress
(
    function (e) {
        //if the letter is not digit then display error and don't type anything
        if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
            //display error message
            $("#errmsg").html("Digits Only").show().fadeOut("slow");
            return false;
        }
    }
);

Nguồn: http://roshanbh.com.np/2008/04/textbox-accept-only-numbers-digits.html

4 Responses to “Accept only positive number using Jquery”

  1. huuthanh3108 says:

    trong Jquery khi viết các hàm thông thường thì phải đặt trong phần có cách nào để viết trong phần không??? ví dụ các hàm như trên

  2. chắc do blog nó chặn ký tự đặc biệt hoặc bạn viết thiếu nên tôi không hiểu “trong phần” của bạn là gì :(

  3. Hoàng Kiên says:

    Tớ thì chơi kiểu thế này
    $.fn.ForceNumericOnly = function(){
    return this.each(function(){
    $(this).keydown(function(e){
    var key = e.charCode || e.keyCode || 0;
    if(e.shiftKey){
    if(key >= 48 && key = 37 && key = 48 && key = 96 && key <= 105) ||
    key == 35 ||
    key == 36);
    })
    })
    };

    Xài: $('.textbox_selector').ForceNumericOnly();

  4. donamkhanh says:

    Hehe.. bản chất đều là check theo keycode. Cách của bạn là viết theo jQuery plugin rùi, pro hơn rất nhiều :p

Leave a Reply