2

I am trying to replace special characters i.e <,>,& from input field on blur and keypress. And the code is working fine but the problem is, once user enter the desired string and then try to edit that string it will move the cursor to the end of the string, So the user isn't able to edit the string in between. How do I make this script more user friendly so that user can edit the existing string from anywhere.

HTML

<input type="text" class="prevent-special" name="name" value="HelloWorld" >

Script

$('.prevent-special').on('keypress blur',function(e){
    //console.log(e.keyCode);
    $(this).val($(this).val().replace(/\<|\>|\&+/g,''));
})  

JS Example

2
  • Issue is with keypress. Why are you using it.? blur is enough Commented Jul 18, 2017 at 8:11
  • @Nimish is it? why? Are you the project sponsor specifying the requirements? Commented Jul 18, 2017 at 8:12

1 Answer 1

2

Try this:

$('.prevent-special').on('keyup blur',function(e){
    var start = this.selectionStart,
        end = this.selectionEnd

    $(this).val($(this).val().replace(/\<|\>|\&+/g,''))

    this.setSelectionRange(start, end)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<input type="text" class="prevent-special" name="name" value="HelloWorld" >

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much, Its work as desired.
You could also change keypress to keyup so the character is never shown in the input. With keypress the cleanup action doesn't get triggered until the next character is typed.
@vi5ion: Thank you. I think keyup fits better.
@vi5ion Thanks I will tack care

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.