简体   繁体   中英

Keypress event : How to detect where the user is typing in the text box

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM