Updating an input's value without losing cursor position

JavascriptJquery

Javascript Problem Overview


I want to mandate that the value of a text box is lowercase using JavaScript. I've tried the code below, but the cursor jumps to the end of the input every time you press a key. How can I avoid this?

$("#beLowerCase").keyup(function(){
    $(this).val( $(this).val().toLowerCase() );
});

Javascript Solutions


Solution 1 - Javascript

$("#beLowerCase").on('input', function(){

    // store current positions in variables
    var start = this.selectionStart,
        end = this.selectionEnd;
    
    this.value = this.value.toLowerCase();

    // restore from variables...
    this.setSelectionRange(start, end);
});

(fiddle)


This actually works with CSS as well:

#beLowerCase{
  text-transform:lowercase;
}

And server can take care of the actual lower-casing...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1318194View Question on Stackoverflow
Solution 1 - Javascriptnice assView Answer on Stackoverflow