I'm working on a function that will insert tags into my textbox. I've modified a script I found online to get it to work almost perfectly. Here's the function:
function insertAtCursor(obj, text1, text2) {
if(obj.selectionStart)
{
var start = obj.selectionStart;
var end = obj.selectionEnd;
if (start == end)
{
obj.value = obj.value.substr(0, start)
+ text1 + text2
+ obj.value.substr(end, obj.value.length);
}
else
{
obj.focus();
obj.value = obj.value.substr(0, end) + text2 + obj.value.substr(end, obj.value.length);
obj.value = obj.value.substr(0,start) + text1 + obj.value.substr(start, obj.value.length);
}
}
}
Here's an example of the parameters:
<a href="#" onClick="insertAtCursor(document.postform.inputfield, '<div id=h1>','</div>')">Header</a>
The function works so that it either inserts "<div id=h1></div>" or those tags around a highlighted substring. The problem is, it won't insert at the 0th position. Meaning to get it to work, I have to insert one character or a space before I click the link to insert the tag. This happens with either of the two methods I described. Is this some sort of off by one error or a kind of bug?