1. 程式人生 > >jquery限制文字框只能輸入數字的方法,適用多種瀏覽器

jquery限制文字框只能輸入數字的方法,適用多種瀏覽器

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
       String path=request.getContextPath();
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--  oninput方法適用於html5、以及高版本的ie瀏覽器,不能直接寫在input框裡,需要用bind繫結-->
   <form action="#">
      郵編:<input id="code" name="code" type="text" value="I"  class="num">
     手機號:<input type="text" id="telephone" name="telephone" value="❤"  maxlength="11" style="color:red" class="num">
     金額:<input type="text" id="money" name="money" id="money" value="You"  class="money">
    <!--  <br> -->
     <input type="button" value="喜歡我就點我吧☺" id="button">
    </form>


</body>
</html>
      <script type="text/javascript" src="<%=path%>/js/importjs/jquery-3.1.0.min.js"></script>
      <script type="text/javascript" src="<%=path%>/js/importjs/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">


//----------------只能輸入數字 Start
/*呼叫    '/限制的正則表示式/g'   必須以/開頭,/g結尾
 *  onkeyup="replaceAndSetPos(this,/[^0-9]/g,'')" oninput ="replaceAndSetPos(this,/[^0-9]/g,'')"
 */
//獲取游標位置
function getCursorPos(obj) {   
    var CaretPos = 0;   
    // IE Support   
    if (document.selection) {   
        obj.focus (); //獲取游標位置函式   
        var Sel = document.selection.createRange ();   
        Sel.moveStart ('character', -obj.value.length);  
        CaretPos = Sel.text.length;   
    }   
    // Firefox/Safari/Chrome/Opera support   
    else if (obj.selectionStart || obj.selectionStart == '0')   
        CaretPos = obj.selectionEnd;   
    return (CaretPos);   
}   
//定位游標    
function setCursorPos(obj,pos)   
{   
    if (obj.setSelectionRange) { //Firefox/Safari/Chrome/Opera  
        obj.focus(); //  
        obj.setSelectionRange(pos,pos);   
    } else if (obj.createTextRange) { // IE  
        var range = obj.createTextRange();   
        range.collapse(true);   
        range.moveEnd('character', pos);   
        range.moveStart('character', pos);   
        range.select();   
    }   
}   
//替換後定位游標在原處,可以這樣呼叫onkeyup=replaceAndSetPos(this,/[^/d]/g,'');     
function replaceAndSetPos(obj,pattern,text){
    if ($(obj).val() == "" || $(obj).val() == null) {
        return;
    }
    var pos=getCursorPos(obj);//儲存原始游標位置   
    var temp=$(obj).val(); //儲存原始值   
    obj.value=temp.replace(pattern,text);//替換掉非法值   
    //截掉超過長度限制的字串(此方法要求已設定元素的maxlength屬性值)  
    var max_length = obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "";  
    if( obj.value.length > max_length){  
            var str1 = obj.value.substring( 0,pos-1 );  
        var str2 = obj.value.substring( pos,max_length+1 );  
        obj.value = str1 + str2;  
    }  
    pos=pos-(temp.length-obj.value.length);//當前游標位置   
    setCursorPos(obj,pos);//設定游標   
    //el.onkeydown = null;
}   
 //-----------------只能輸入數字 end


 $(function(){
     //繫結oninput事件 只能輸入數字  propertychange低版本ie的方法
      $(function(){
          //郵箱 手機號
           $(".num").each(function(){
              $(this).bind('input propertychange',function(){
                  replaceAndSetPos(this,/[^0-9]/g,'');
              })
          });
          //金額
          $(".money").bind('input propertychange',function(){
              replaceAndSetPos(this,/[^\-?0-9\.]/g,'');
          });
          
          
      });
 });
 
 
 
 
 
 
 
 
 
 $("#button").click(function(){
     alert("老婆大人,您別生氣了,不要不bird我好不好")
 });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

</script>