Search code examples
javascriptjquerytextfieldkeypress

detecting last entered character's index number in a textfield


I'm getting the last entered character in textfield "message" by the code below:

$('#message').on("keypress", function(event) {
              var a= String.fromCharCode(event.which);}

I also want to get the index number of the last entered character but can't find any solution. I tried some combinations with indexOf and findIndex but couldn't get them to work.


Solution

  • You can get it target.selectionStart method, like this:

    $('#message').on("keypress", function(event) {
        var a = String.fromCharCode(event.which);
        console.log("Char:" + a, "Position:" + event.target.selectionStart);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" id="message" value=""/>