Sealyu

          --- 博客已遷移至: http://www.sealyu.com/blog

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            618 隨筆 :: 87 文章 :: 225 評論 :: 0 Trackbacks

          Few days back, my friend Parleen asked me how can we make a textbox which just accepts only numbers specially digits only. And, for his I come up with this solution of textbox which only accepts digits, and if you try to enter any alpha bates in it then it displays the error message with animation.

          View Demo

          HTML Code

          <input type="text"name="quantity"id="quantity"/><span id="errmsg"></span>

          As you can see above, I’ve given the name and id of textbox to “quantity” in this example.This is the textbox which only accepts numbers (digits only). You can see “span” after textbox which is used to display the error message with fading effect using jQuery.

          Javascript Code

          First of all, we need to use jQuery library as we’re using the jquery’s function to accept only digits.

          <script type="text/javascript"src="jquery.js"></script>

          Now le’ts write the code in JavaScript using jQuery to accept only digits in textbox and displaying error with animation.

          //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");

              returnfalse;

            }

          });

          When the key is pressed, we’re using the key’s ASCII value to check which button is pressed. In first expression, delete, tab or backspace button is is checked and “8″ is the ASCII values of the Back-space. Digits are checked in the second expression. “48″ is the ASCII values of “0″ and “57″ is the ASCII values of “9″. The the ASCII values of the other digits lies between “48″ to “57″. And, if the key pressed values doesn’t lies withing these range, then we are displaying the error message with jQuery’s fading effect.

          And, the “return false” statement means that this functions returns false values which means not to type anything on the text box.

          Download Full Source Code

          posted on 2009-11-06 17:46 seal 閱讀(389) 評論(0)  編輯  收藏 所屬分類: JQuery
          主站蜘蛛池模板: 大名县| 吐鲁番市| 兴安盟| 宜川县| 石柱| 玉田县| 若尔盖县| 遂川县| 武邑县| 延津县| 麻栗坡县| 平凉市| 朝阳县| 青神县| 温宿县| 芷江| 怀仁县| 嘉兴市| 萍乡市| 东阳市| 逊克县| 黑河市| 克拉玛依市| 宁海县| 临泽县| 沙洋县| 休宁县| 阜新市| 泊头市| 美姑县| 鄂尔多斯市| 措美县| 金坛市| 新源县| 灵宝市| 申扎县| 普洱| 阿坝| 凌源市| 枣庄市| 资阳市|