User:Joeytje50/tabinsert.js

// http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/ function getCaretPos(ctrl) { var CaretPos = 0;   // IE Support if (document.selection) { ctrl.focus ; var Sel = document.selection.createRange ; Sel.moveStart ('character', -ctrl.value.length); CaretPos = Sel.text.length; }   // Firefox support else if (ctrl.selectionStart || ctrl.selectionStart == '0') CaretPos = ctrl.selectionStart; return (CaretPos); } function setCaretPos(ctrl, pos){ if(ctrl.setSelectionRange) {       ctrl.focus; ctrl.setSelectionRange(pos,pos); }   else if (ctrl.createTextRange) { var range = ctrl.createTextRange; range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select; } }

//Tab insert for usernames $('#searchInput').after(' [0,"","",0] '); document.getElementById('searchInput').onkeydown = function(e) { if (e.keyCode == 9) { e.preventDefault; var curval = this.value; var afData = eval(document.getElementById('autofilldata').innerHTML); var curpos = afData[3]==0?getCaretPos(this):afData[3]; if ((!curval.charAt(getCaretPos(this))||curval.charAt(getCaretPos(this)).match(/\s/))&&!curval.charAt(getCaretPos(this)-1).match(/\s/)) { var unamestart = ''; if (afData[1].length==0) { for (i=curpos-1;i>=0&&!curval.charAt(i).match(/\s/);i--) { unamestart = curval.charAt(i) + unamestart; }			} else { unamestart = afData[1]; }			var afterTComplete = ''; for (i=curpos;i<curval.length;i++) { afterTComplete += curval.charAt(i); }			//generate list of users var userList = []; var userlistelems = document.getElementsByClassName('User'); for (i=0;i<userlistelems.length;i++) { userList.push(userlistelems[i].getElementsByClassName('username')[0].innerHTML); }			userList.sort; userList[userList.indexOf(wgUserName)] = ''; var matchedNames = []; for (i=0;i=matchedNames.length-1?0:afData[0]+1; document.getElementById('autofilldata').innerHTML = '['+iter+',"'+unamestart+'","'+matchedNames[afData[0]]+'",'+curpos+']' }		return false; } else { document.getElementById('autofilldata').innerHTML = '[0,"","",0]'; } }; //when clicking on the input (so moving the caret), reset the tabcomplete document.getElementById('searchInput').onclick = function { document.getElementById('autofilldata').innerHTML = '[0,"","",0]'; }​ //when focus is away from the input, reset the tabcomplete document.getElementById('searchInput').onblur = function { document.getElementById('autofilldata').innerHTML = '[0,"","",0]'; }​