UI AutoComplete Multiple Demo - Caret Position in IE

UI AutoComplete Multiple Demo - Caret Position in IE

While attempting to implement an autocomplete widget similar to the " Multiple values " and " Multiple, remote " demos on the jQuery UI website, I discovered a minor issue when using the autocomplete field in Internet Explorer (tested in IE7 and IE8).

Once the user selects an item from the autocomplete dropdown, the caret (cursor) position in the text field resets to the beginning of the text field, rather than moving to the end of the value.

Because of this, if the user is not savvy enough to realize that the cursor is in the wrong place, they will most likely end up trying to type a second value that, instead of being recognized as a separate value, just gets prepended to the first selected value. For instance, let's say I type "ja" and then select "javascript" from the autocomplete dropdown. Once I've selected "javascript", I start typing "co". In IE, the value of the text input will now look like:

  1. cojavascript, 
instead of:
  1. javascript, co

To battle this issue, I have added the following code just below this.value = terms.join(", ");

  1. if(document.selection) {
  2.   this.focus();
  3.   var oSel = document.selection.createRange();
  4.   oSel.moveStart('character',this.value.length);
  5.   oSel.moveEnd('character',0);
  6.   oSel.select();
  7. }
I'm sure there's probably a more elegant solution, but this seems to work for now. If you have any better suggestions, please let me know. Hopefully something can be added to the widget itself to make sure that the caret always ends up at the end of the text field after selecting an item. Thank you.