2017-03-09 95 views
0

我對javascript或jquery不是很有經驗。我需要確定用戶的光標是否處於文本輸入字段的最後一個位置,在鍵入時最大長度爲3。如果是這樣,請將焦點切換到下一個字段。我已經在表單上看到了很多,所以我認爲每個人都可以理解我正在尋找的常用功能。問題的輸入字段不是文本類型,但是類型爲tel在鍵上獲取光標位置

我試圖在這裏找到這個問題的答案,但我無法理解任何可能是類似問題的答案,米問,但不完全一樣。例如,它提到了selectionStart和selectionEnd,但我無法找到真正解釋的地方。在我看來,它們涉及選定的文本,但這不是我想要的。

我希望在用戶輸入時進行檢查。以下是我試圖查看是否可以返回正確的值,但返回的值未定義。

$("#phone1").keyup(function(){ 
    var phone = $("#phone1"); 
    alert(phone.selectionEnd); 
}); 

對不起,如果我不明白這一些。任何援助將不勝感激。謝謝。

回答

0

這是你在找什麼?

(function ($, undefined) { 
     $.phone1.getCursorPosition = function() { 
      var el = $(this).get(0); 
      var pos = 0; 
      if('selectionStart' in el) { 
       pos = el.selectionStart; 
      } else if('selection' in document) { 
       el.focus(); 
       var Sel = document.selection.createRange(); 
       var SelLength = document.selection.createRange().text.length; 
       Sel.moveStart('character', -el.value.length); 
       pos = Sel.text.length - SelLength; 
      } 
      return pos; 
     } 
    })(jQuery); 

    $("#phone1").on('keypress', function(e){ 
     var key = String.fromCharCode(e.which); 
     if(key === '*') { 
      var position = $(this).getCursorPosition(); 
      console.log(position); 
     } else { 
      return false; 
     } 
    });​ 

字體:Get keyup position using jquery是非常相似的,我認爲..

+0

只要看看鏈接,如果你有問題..這是非常相似的你的。 – JustARandomProgrammer

0

基本上,你應該綁定jQuery的事件是「改變」事件,這將觸發對將要發生像新的輸入的每一個變化,或刪除輸入等。

eg

(function(){ 

    $('#telNo').on('input' , function(){ 
      if($(this).val().length == $(this).attr('maxlength')) 
      $(this).next('input').focus(); 
    }); 

})(); 
在上面的代碼

,這個代碼將焦點轉移到下一個輸入,而不管類型

$(this).next('input').focus(); 

和HTML標記應該是這樣的:

<input type="tel" maxlength="4" id="telNo"> 
<input type="text" maxlength="4" id="text"> 

這裏是工作小提琴

JS Fiddle