2016-02-16 28 views
-1

我有一個輸入字段,我需要弄清楚用戶正在鍵入的最後一個字符是什麼。這可能是輸入中的最後一個字母,但它也可以位於輸入字段中的任何位置。jQuery:獲取輸入字段的最後更改

我需要的是這樣的:

var timerid;  
    $("#input").on("propertychange change click keyup input paste",function(e){ 
     var value = $(this).val(); 
     if($(this).data("lastval")!= value){ 
      $(this).data("lastval",value); 

      //console.log(difference between lastval and value or something similar to get the last character the user types in the input) 

      clearTimeout(timerid); 
      timerid = setTimeout(function() { 

       //change action 
       console.log(value);    
       input_array(value) 

      },400); 

     }; 
    }); 
+0

Offtopic!你不想說'如果lastval =價值'在那裏,否則,如果你繼續按下相同的鍵,你會得到多個(仍然是反彈,但多個)console.logs爲同樣的關鍵,而不僅僅是最後一個。 –

+0

如果用戶粘貼了整個單詞,你會在'input_array'中存儲什麼?或者他們選擇一些文字並按下ctrl-x。除「最後更改」之外,您可能希望將您的要求定義得更清晰一些。最後輸入的字符是?那你爲什麼在你的例子中有'propertychange'和'paste'? –

+0

謝謝,這是關於用戶在這裏輸入的最後一個字符。但是輸入也可以用來粘貼某些東西。 – buckdanny

回答

1

只需使用​​事件和String.fromCharCode方法

$('input').on('keydown', function(event) { 
 
    $('#key-entered').html(String.fromCharCode(event.keyCode)); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type='text' /> 
 

 
<p id='key-entered'>

相關問題