html如何控制input只能输入数字

时间:2022-11-05 12:15:59
<input id="Text1" type="text" onkeypress="return IsNum(event)" />
    <script language="javascript" type="text/javascript">
        function IsNum(e) {
            var k = window.event ? e.keyCode : e.which;
            if (((k >= 48) && (k <= 57)) || k == 8 || k == 0) {
            } else {
                if (window.event) {
                    window.event.returnValue = false;
                }
                else {
                    e.preventDefault(); //for firefox 
                }
            }
        } 
    </script>




<tr>
    <td class="label">{$lang.brand_am}</td>
    <td><span>小时:</span><input type="text" name="brand_am_h" id="brand_am_h" maxlength="5" size="5" onkeypress="return IsNum(event,'brand_am_h',2,3,4)" value="{$brand.brand_am_h}"/><span>分钟:</span><input type="text" name="brand_am_i" id="brand_am_i" onkeypress="return IsNum(event,'brand_am_i',5,6,9)" maxlength="5" size="5" value="{$brand.brand_am_i}"/></td>
  </tr>
  <tr>
    <td class="label">{$lang.brand_pm}</td>
    <td><span>小时:</span><input type="text" name="brand_pm_h" id="brand_pm_h" maxlength="5" size="5" onkeypress="return IsNum(event,'brand_pm_h',2,3,4)" value="{$brand.brand_pm_h}"/><span>分钟:</span><input type="text" name="brand_pm_i" id="brand_pm_i"  onkeypress="return IsNum(event,'brand_pm_i',5,6,9)" maxlength="5" size="5" value="{$brand.brand_pm_i}"/></td>
  </tr>
<script language="javascript" type="text/javascript">
        function IsNum(e,id,num1,num2=9,num3=9) {
            var k = window.event ? e.keyCode : e.which;
            var temp_num3 =48+num3;
            if (((k >= 48) && (k <= 57)) || k == 8 || k == 0) {
                var temp_var = document.getElementById(id).value;
                if((temp_var >= num2) && (k != 8)){
                     if (window.event) {
                            window.event.returnValue = false;
                        }
                        else {
                            e.preventDefault(); //for firefox 
                        }
                }else if((temp_var == num1) && (k != 8) && (k > temp_num3)){
                     if (window.event) {
                            window.event.returnValue = false;
                        }
                        else {
                            e.preventDefault(); //for firefox 
                        }
                }
            } else {
                if (window.event) {
                    window.event.returnValue = false;
                }
                else {
                    e.preventDefault(); //for firefox 
                }
            }
            
        } 
    </script>