1

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.

  • Duplicate: http://stackoverflow.com/questions/14508707/updating-an-inputs-value-without-losing-cursor-position – code4pi Apr 20 '16 at 03:54
  • I think the above solution is probably correct. Can you confirm that this is what you're speaking of? – Dale Apr 20 '16 at 04:07

1 Answers1

1

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();
});