ntwiles Posted August 31, 2010 Share Posted August 31, 2010 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? Quote Link to comment Share on other sites More sharing options...
RussellReal Posted August 31, 2010 Share Posted August 31, 2010 why not try this: obj.value += text1 + text2 + obj.value.substr(end, obj.value.length); also note, I really don't see a problem with the code above, if anything the substr is giving you a pain in the balls because it has no data to manipulate oh sorry.. edit #2.. scratch the above.. just add in a clause.. if (obj.value.length) { obj.value += text1+text2; } else { //do ur code } Quote Link to comment Share on other sites More sharing options...
Adam Posted August 31, 2010 Share Posted August 31, 2010 That'll be because the .selectionStart property equals 0. Your IF expression evaluates to false because 0 == false. An easy way in your situation to get around the problem would be to just check if the property is defined, as opposed to true: if (obj.selectionStart != undefined) Quote Link to comment Share on other sites More sharing options...
ntwiles Posted August 31, 2010 Author Share Posted August 31, 2010 Awesome, that was it. I love when a solution comes down to just one simple error. Thanks a lot for the help guys. This one has been bugging me for half a week. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.