93

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() );
});
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260

1 Answers1

144
$("#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...

nice ass
  • 16,471
  • 7
  • 50
  • 89
  • luckily, I don't have to care about IE :) –  Jan 24 '13 at 19:18
  • @onetrickpony, If this only works onkeyup, what happens when the user right click paste? – Pacerier Jul 24 '14 at 13:29
  • 6
    There is a reason why I hate jQuery, it's because everyone uses it when it's not really necessary at all. – Iharob Al Asimi May 30 '15 at 15:49
  • Note that when you're using jQuery selector, you need to call `selectionStart` on the DOM element. That means you need to do `$("#someId").get(0).selectionStart`. – Micer Aug 11 '15 at 15:03
  • 1
    For Safari: do not trigger this lowercasing function with `onblur`, because otherwise the input will keep the focus forever – Sebastien Lorber Aug 12 '15 at 09:38
  • 2
    Don't forget to take in account the changed cursor position when using this technique to strip characters. If the length of the value changes before setting the selectionRange, the difference in length should be substracted from the start and end of the selection. – Dreamdealer May 24 '16 at 08:24