Jump to content

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/212154-insert-substring-function/
Share on other sites

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
  }

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)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.