View Full Version : Insert Tags Into Textarea. What could I improve?

10-20-2005, 11:21 PM
I'm writing a tag-based php/javascript cms thing and I just implemented this "insert text at cursor" script that I wrote and modified from various sources and tutorials online. I need something cross-browser compliant.

Check out the second function. I'd like to get some outside opinions.. Anything you see that needs tightened up? If there's no insb variable on the second function, certain versions of PC IE do nothing at all. I like to use Safari, and I've seen no way to get that to work, sadly.

function getOccurances(needle,haystack) {
var whereiam=haystack.indexOf(needle);
var number=0;
var lenofneedle=needle.length - 1;
if(whereiam!=-1) {
while(whereiam!=-1) {
return number;
} //getOccurrances

function insertaroundselect(el,insa,insb) {

if(insb) { //there is a second thing to insert
var numbera=getOccurances(insa,el.value);
var numberb=getOccurances(insb,el.value);
var toinsert=insa;
if(numbera>numberb) toinsert=insb;

//Browser has setSelectionRange
if (el.setSelectionRange){
if(el.selectionStart==el.selectionEnd) { // cursor not selection
if(el.selectionStart==el.value.length) el.value+=toinsert; //if at end, just insert correct next piece
else el.value=el.value.substring(0,el.selectionStart) + toinsert
+ el.value.substring(el.selectionStart,el.value.length);
else el.value= el.value.substring(0,el.selectionStart) + insa
+ el.value.substring(el.selectionStart,el.selectionEnd) + insb
+ el.value.substring(el.selectionEnd,el.value.length);

//Browser has createRange
else if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
if(range.length<2) range.text= toinsert;
else range.text = insa + range.text + insb;

//Browser Sucks (safari) :(
else el.value+= toinsert;
} //there is a second thing to insert.

else { //there is only one item to insert
if(el.setSelectionRange) el.value=el.value.substring(0,el.selectionStart) + insa + el.value.substring(el.selectionStart,el.value.length);
else if(document.selection && document.selection.createRange) {
var range=document.selection.createRange();
if(range.length<2) range.text=insa+range.text;
else el.value+=insa;
} //there is only one item to insert