Stop cursor from jumping to end of input field in javascript replace

后端 未结 3 967
盖世英雄少女心
盖世英雄少女心 2020-11-27 05:29

I\'m using a regular expression to strip invalid characters out of an text input area in javascript (running in IE). I run the replace function on every keyup event. However

3条回答
  •  日久生厌
    2020-11-27 06:11

    I was running into the same issue, I found https://www.sitepoint.com/6-jquery-cursor-functions/ had the solution. here are 6 methods that will allow you to get/set the cursor position in an input/textarea. I believe this will work for content editable fields as well!

    This was very helpful as the bug only showed for IE and Windows 7 combination.

    Here is my Before code

    $body.on('input paste','.replace-special-chars',function () {
        let coma = /‚/g;
        let doubleQuotes = /[“”]/g;
        let singleQuotes = /[‘’]/g;
        $(this).val($(this).val().replace(doubleQuotes,'"'));
        $(this).val($(this).val().replace(coma,','));
        $(this).val($(this).val().replace(singleQuotes,"'"));
        $(this).val($(this).val().replace(/[^\x00-\xff]/g, '- '));
    });
    

    and my after code which utilizes the jquery methods that I found on the website I stated above

    $body.on('input paste','.replace-special-chars',function () {
        let position = $(this).getCursorPosition();
        let coma = /‚/g;
        let doubleQuotes = /[“”]/g;
        let singleQuotes = /[‘’]/g;
        $(this).val($(this).val().replace(doubleQuotes,'"'));
        $(this).val($(this).val().replace(coma,','));
        $(this).val($(this).val().replace(singleQuotes,"'"));
        $(this).val($(this).val().replace(/[^\x00-\xff]/g, '- '));
        $(this).setCursorPosition(position);
    });
    

提交回复
热议问题