user1372430
user1372430

Reputation:

Cursor position abnormally situated at the end of the input value in Chrome

I coded a jQuery function to remove automatically single and double quotes while writing text in to input box. In firefox everything goes good but in Chrome, if you want to add something beginning of the text, it is not allowed. Because the cursor always situated at the end of the input value. I don't know how I fix it. Here is my code:

$.fn.removeQuotes = function()
{
    var elem = $(this);
    elem.bind("focus propertychange change click keyup input paste", function(event)
    {
        setTimeout(function ()
        {
            elem.val(elem.val().replace(/['"]/g, ""));
        }, 1);
   });
};

EDIT: After comments, I tried this:

$.fn.removeQuotes = function()
{
    var elem = $(this);
    elem.bind("focus propertychange change click keyup input paste", function(event)
    {
        // store current positions in variables
        var start = this.selectionStart,
        end = this.selectionEnd;
        setTimeout(function ()
        {
            elem.val(elem.val().replace(/['"]/g, ""));
        }, 1);
       // restore from variables...
       this.setSelectionRange(start, end);
   });
};

But nothing changed.

Upvotes: 1

Views: 86

Answers (1)

Sanjeevi Rajagopalan
Sanjeevi Rajagopalan

Reputation: 232

Here's a crude version for you to build on - https://jsfiddle.net/Sanjeevi/79gun3g0/1/

    <div>
      <input id="text-box" type="text">
    </div>

$.fn.removeQuotes = function()
{
    var elem = $(this);
    elem.bind("keyup", function(event)
    {
                var start = elem.caret();
            console.log(start);
            elem.val(elem.val().replace(/['"]/g, ""));
            setCaretPosition('text-box',start);
   });
};

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

$(document).ready(function(){
    $("#text-box").removeQuotes();
});

Upvotes: 1

Related Questions