RobinHerbots / Inputmask

Input Mask plugin
https://robinherbots.github.io/Inputmask/
MIT License
6.4k stars 2.16k forks source link

Cursor jumps to the left for MS Edge and contenteditable #2178

Open ElenaSokolyk opened 5 years ago

ElenaSokolyk commented 5 years ago

Hi! I have issue when cursor jumps to the left when it should stay at the end of line. For example, when I try to enter 1,234.67 I get 17,234.6.

can simulate it on browserstack Windows 10 MS Edge 18. https://jsfiddle.net/ydab8x5s/

<div contenteditable="true" id="money">
</div>

$(function(){
  $('#money').inputmask('currency', {
    digits: 4,
    digitsOptional: true,
    prefix: '',
    rightAlign: false
  });
});
knoxcard commented 5 years ago

Try this for now...maybe not a 100%, let me know your thoughts... https://jsfiddle.net/f98qd4u1/1/

$.fn.setCursorPosition = function(pos) {
  this.each(function(index, elem) {
    if (elem.setSelectionRange) {
      elem.setSelectionRange(pos, pos)
    }
    else if (elem.createTextRange) {
      var range = elem.createTextRange()
      range.collapse(true)
      range.moveEnd('character', pos)
      range.moveStart('character', pos)
      range.select()
    }
  })
  return this
}
$.fn.getCursorPosition = function() {
  var pos = 0,
    el = $(this).get(0)
  if(document.selection) {
      el.focus()
      var Sel = document.selection.createRange()
      var SelLength = document.selection.createRange().text.length
      Sel.moveStart('character', -el.value.length)
      pos = Sel.text.length - SelLength
  }
  else if(el.selectionStart || el.selectionStart == '0')
      pos = el.selectionStart
  return pos
}

$(function(){
    $('#money').inputmask('currency', {
 digits: 4,
    digitsOptional: true,
    prefix: '',
    rightAlign: false
  });
  $('#money').on('input', function() {
    var curr_pos = $(this).getCursorPosition()
    setTimeout(function() {
      $(this).setCursorPosition(curr_pos)
    }, 1)
  }) 
});
RobinHerbots commented 5 years ago

Hi @ElenaSokolyk ,

Can you have a try with the latest version 5.x beta. See this https://jsfiddle.net/outmf918/

With a contenteditable div there seems to be an issue in jsfiddle, but I cannot reproduce this locally. Can you have a try locally and see if there are any issues with contenteditables.

best regards, Robin