jQuery:获取输入字段的最后一次更改

时间:2016-02-16 22:40:41

标签: 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);

        };
    });

2 个答案:

答案 0 :(得分:1)

只需使用keydown事件和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'>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

另一种方式可能是.key

请注意,整个浏览器都不支持see compatibility details

$('input').on('keydown', function(event) {
    console.log(event.key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />

相关问题