0

I'm in a situation where user I need to run some validations while user types and restrict him not to enter beyond a limit.

I'm using a key press event for this.

$(document).on('keypress', "#range", function (e) {});

Here is the example I've worked out.

Its working fine when the user is appending to the existing value, but when user changes it by prepending or editing in middle. So how can i detect the cursor position(index) while user is typing. At the same time how to know if the entire text in the textbox is selected or not.

Strikers
  • 4,698
  • 2
  • 28
  • 58

1 Answers1

0

In your case, you should actually calculate the selection range using window.getSelection().

$(document).on('keypress', '#range', function (e) {
    var sel = document.getSelection();
    var keyCode = e.which || e.keyCode;
    var pressedChar = String.fromCharCode(keyCode);
    var start = sel.extentOffset;
    var end = sel.baseOffset;
    var str = this.innerHTML;

    // Then later magic!! 
    // Source: http://stackoverflow.com/a/1431113/1577396
    var curValue = str.substr(0, start) + pressedChar + str.substr(end);

    // other code
});

Working Fiddle

Mr_Green
  • 40,727
  • 45
  • 159
  • 271