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?
HTML page
Javascript file
Code:
Error: document.selection is undefined Source File: system.js Line: 11
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>
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;
}
Comment