Adding text at cursor position in textarea

Advert test
#1
I'm using the below function to add in a <br/> tag to the cusrors current position when the button is clicked, its adding in the <br/> at the begining everytime and not where the cursor is, I'm gettin the blow error but unable to figure out whats wrong, anyone any ideas?

Code:
Error: document.selection is undefined
Source File: system.js
Line: 11
HTML page
Code:
<form name="form">
    <input type="button" value="Add Line Break" onclick="insertString('<br/>');"/><br/><br/>
    <textarea cols="30" rows="20" name="large_profile" onchange="setCursorPos()" onclick="setCursorPos()"></textarea>
</form>
Javascript file
Code:
var globalCursorPos; // global variabe to keep track of where the cursor was

function setCursorPos() {
 globalCursorPos = getCursorPos(document.form.large_profile);
}

function getCursorPos(textElement) {

 var sOldText = textElement.value;

 var objRange = document.selection.createRange();
 var sOldRange = objRange.text;

 var sWeirdString = '#%~';

 objRange.text = sOldRange + sWeirdString; objRange.moveStart('character', (0 - sOldRange.length - sWeirdString.length));

 var sNewText = textElement.value;

 objRange.text = sOldRange;

 for (i=0; i <= sNewText.length; i++) {
   var sTemp = sNewText.substring(i, i + sWeirdString.length);
   if (sTemp == sWeirdString) {
     var cursorPos = (i - sOldRange.length);
     return cursorPos;
   }
 }
}

function insertString(stringToInsert) {
 var firstPart = document.form.large_profile.value.substring(0, globalCursorPos);
 var secondPart = document.form.large_profile.value.substring(globalCursorPos, document.form.large_profile.value.length);
 document.form.large_profile.value = firstPart + stringToInsert + secondPart;
}
I've found that this works fine in IE but theres an issue with FF browser using the selection code correctly, is there a way to get this function working in both IE and FF?
 

louie

New Member
#2
to ad at the end you need to capture the value inside the textarea, ad the <br /> tag and replace with the new value.
 
#3
I can add the <br/> to the end no problem. The code I posted above I'm using to add the <br/> tag where th cursor currently is in the text area, say a user types out a load of text and then click in the middle and wants to add a <br/> tag. The code above works in IE but not in FF, any ideas?
 
#4
Getting a lot further, I'm using the below function now and it works for IE for the firefox(and other browsers bit) isn't. Can anyone tell me where I'm going wrong?

Code:
var objRange
 if (navigator.userAgent.indexOf("MSIE")!=-1) {
  objRange = document.selection.createRange();
 }
 //else if (navigator.userAgent.indexOf("Firefox")!=-1) {
 else {
  document.getElementById('large_profile').selectionStart;
  document.getElementById('large_profile').selectionEnd;
  objRange = document.getElementById('large_profile')
 }
 var sOldRange = objRange.text;
 
Top