I wrote this very little pice of code several times now, because i lost it each time again. Hopefully i find it next time here…
So what to do if you want to preset an selection within an input or textarea, just to support your users a little ( which they will never recognize – of course, they are users and do expect these things ). We’re lucky, Mozilla and IE also have little methods for that:
/** * @description setSelection - sets an selection for end input from start to end- index * $Id: range_selection.js 2 2009-03-17 19:25:27Z dinnerout $ * @param node DOM-Node/String - DOM-Node or Id of Node to set selection in * @param startIndex Int - Startindex od selection * @param length Int - length of selection */ function setSelection( node, startIndex, length ){ var dNode = (typeof node == 'string')?$(node):node; dNode.focus(); // IE if(document.selection){ var range = document.selection.createRange(); range.move('character',-10000000); // reset cursor position range.moveStart('character',startIndex); range.moveEnd('character',startIndex+length); range.select(); } // Mozilla if(dNode.selectionStart){ dNode.selectionStart = startIndex; dNode.selectionEnd = startIndex + length; } } |