在不丢失光标位置的情况下更新输入值

我希望使用 JavaScript 命令文本框的值为小写。我试过下面的代码,但是每次按下一个键,光标就会跳到输入的末尾。我怎样才能避免这种情况呢?

$("#beLowerCase").keyup(function(){
$(this).val( $(this).val().toLowerCase() );
});
52245 次浏览
$("#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...