只允许脚本数字和点 [英] Allow only numbers and dot in script

查看:114
本文介绍了只允许脚本数字和点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个JavaScript用于限制用户键入数字和只有一个点作为小数点分隔符。

Am using this javascript for restrict users to type only numbers and only one dot as decimal separator.

<script type="text/javascript">
 function fun_AllowOnlyAmountAndDot(txt)
        {
            if(event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 46)
            {
               var txtbx=document.getElementById(txt);
               var amount = document.getElementById(txt).value;
               var present=0;
               var count=0;

               if(amount.indexOf(".",present)||amount.indexOf(".",present+1));
               {
              // alert('0');
               }

              /*if(amount.length==2)
              {
                if(event.keyCode != 46)
                return false;
              }*/
               do
               {
               present=amount.indexOf(".",present);
               if(present!=-1)
                {
                 count++;
                 present++;
                 }
               }
               while(present!=-1);
               if(present==-1 && amount.length==0 && event.keyCode == 46)
               {
                    event.keyCode=0;
                    //alert("Wrong position of decimal point not  allowed !!");
                    return false;
               }

               if(count>=1 && event.keyCode == 46)
               {

                    event.keyCode=0;
                    //alert("Only one decimal point is allowed !!");
                    return false;
               }
               if(count==1)
               {
                var lastdigits=amount.substring(amount.indexOf(".")+1,amount.length);
                if(lastdigits.length>=2)
                            {
                              //alert("Two decimal places only allowed");
                              event.keyCode=0;
                              return false;
                              }
               }
                    return true;
            }
            else
            {
                    event.keyCode=0;
                    //alert("Only Numbers with dot allowed !!");
                    return false;
            }

        }

    </script>

<td align="right">
<asp:TextBox ID="txtQ1gTarget" runat="server" Width="30px" CssClass="txtbx" MaxLength="6" onkeypress="return fun_AllowOnlyAmountAndDot(this);"></asp:TextBox>
</td>

不过,安其preSS(本)事件返回在这个地方对象在功能所需误差

But the onkeypress(this) event returns object required error in that function at this place

var amount = document.getElementById(txt).value;

什么是我的错吗?

What's my mistake here?

推荐答案

而不是使用这个的:

安其preSS =返回fun_AllowOnlyAmountAndDot(本);

您应该使用这样的:

安其preSS =返回fun_AllowOnlyAmountAndDot(this.id);

这篇关于只允许脚本数字和点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆