0

I am trying to convert the characters in the textbox to upper case.

But this seems to affect my cursor position.

JS fiddle below:

$(this).val($(this).val().toUpperCase());

http://jsfiddle.net/ZdRnZ/

If I type on a blank textbox everything is fine... but If i try to type inbetween the text the cursor immediately goes to the end of the word.

How can I prevent it from happening, my cursor should be where I stopped typing, not at the end of the text.

Works fine in Firefox, IE screws it up. I need it working on IE

Haran Murthy
  • 341
  • 2
  • 10
  • 30
  • http://plugins.jquery.com/project/jCaret – Benjam Nov 30 '12 at 23:43
  • http://stackoverflow.com/questions/2897155/get-caret-position-within-an-text-input-field – Benjam Nov 30 '12 at 23:45
  • Actually, it happens in firefox too. I would just convert to uppercase on .blur() http://jsfiddle.net/ZdRnZ/3/ – VIDesignz Nov 30 '12 at 23:46
  • Answer can possibly be found in here: [jQuery: Get the cursor position of text in input without browser specific code?](http://stackoverflow.com/questions/4085312/jquery-get-the-cursor-position-of-text-in-input-without-browser-specific-code) and here: [how can i get cursor position in a textarea?](http://stackoverflow.com/questions/1891444/how-can-i-get-cursor-position-in-a-textarea) (this one look at the higher voted answer instead of accepted one) – Nope Nov 30 '12 at 23:46
  • Why don't wait that the user has finished to write is sentence and when the inputbox lost the focus apply the uppercase to all the text. – freedev Nov 30 '12 at 23:50

2 Answers2

5

This can also be accomplished via CSS:

<input style="text-transform: uppercase" type='text'></input>

Put this in your HTML page and the textbox will force all text input to be uppercase. There are additional modifiers:

lowercase, capitalize, none, inherit

Of course, this can be browser-dependent, but seems to be supported in most browsers.

I have updated your sample adding the text-transform style and switching the jquery event bind from keyup to change : http://jsfiddle.net/ZdRnZ/6/

freedev
  • 25,946
  • 8
  • 108
  • 125
1

$('#txt').keyup(function (e) {
  var position, texto, code;
  texto=this.value;
  code=e.keyCode;   
  position=texto.slice(0, this.selectionStart).length;       
  if((code>=65 && code <=90 )|| code ==192 ){
    this.value=texto.toUpperCase();
    this.setSelectionRange(position,position);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txt" style="width:100%" />
etel
  • 11
  • 1