Code Bug Fix: Problem with regex expressions and Jquery on Input events

Original Source Link

having a problem using regular expression to allow only certain characters. The problem is when i try to insert a character into words to correct errors. When i try to insert the new char the cursor move to the end of the input box.

this is the code i use:

$('body').on('input','.info',function() {
        this.value = this.value.replace(/[^a-zA-Z0-9+&,*_- b r ]/g, '');

Any hints?

Thank you in advance

You need to save the character index (the selectionStart) so you can reposition to it after value change is complete, if a value change needs to be made:

$('body').on('input', '.info', function(e) {
  const index = this.selectionStart - 1;
  const replaced = this.value.replace(/[^a-zA-Z0-9+&,*_- b r ]/g, '');
  if (replaced !== this.value) {
    this.value = replaced;
    this.selectionStart = index;
    this.selectionEnd = index;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="info">
Tagged : / /

Leave a Reply

Your email address will not be published. Required fields are marked *