1

I'd like to get the last deleted character on a backspace event, so that I can modify some other div accrodingly. The function that I'm looking for is like:

$('.tags').keyup(function (e) {
   if (e.keyCode == 8) {
    var t = e.target;
    let deletcChar = //find the deleted character
        console.log("deleted char is:", deletedChar);
        //do something about deletcChar             
    }
});

the solutions that I found here (like this) are all massively complicated and based on keydown.

A simpler solution here uses (e.target.value[even.target.selectionStart - 1]) which does not work for keyup.

So I'm wondering if there is a strighforward way for keyup() in jquery?

Babr
  • 1,971
  • 14
  • 33
  • 47

1 Answers1

2

You can set a data-attribute on page load to store the last state, then find the deleted character from that every time it's updated

$(document).ready(function() {
  $('.tags').each(function() {
    $(this).attr('data-laststate', $(this).val())
  })
  $('.tags').keyup(function(e) {
    if (e.keyCode == 8) {
      let deletedChar = $(this).attr('data-laststate').slice(-1);
      console.log("deleted char is:", deletedChar);
    }
    $(this).attr('data-laststate', $(this).val())
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class='tags' value='php,html,asp' />
Kinglish
  • 23,358
  • 3
  • 22
  • 43