Jump to content

Length of a range in IE


joe92

Recommended Posts

What I am trying to achieve is to insert tags around selected text. It is dead easy in all browsers except IE :'( (typical)

 

I think I have it pretty much sussed, except that the js wont calculate the length of a range. This is the code (adapted from this, excuse the many notes):

 

postArea.focus();
/*IE route*/
if(document.selection)
{
if(postArea.createTextRange && postArea.caretPos)
	{
		  /* create range */
		var range = document.selection.createRange();
		  /* length of range */
		var range_length = range.text.length;
		alert(range_length);
		  /*create 'dummy'*/
		var stored_range = range.duplicate();
		  /*select all text*/
		stored_range.moveToElementText( postArea );
		  /*move 'dummy' end point to end point of original range*/
		stored_range.setEndPoint('EndToEnd', range);
		  /*the start and end points of selection*/
		postArea.selectionStart = stored_range.text.length - range_length;
		postArea.selectionEnd = postArea.selectionStart + range_length;
		  /*determine what is selected*/
		var selection = postArea.value.substring(postArea.selectionStart, postArea.selectionEnd);
		  /*where to place the cursor*/
		var insertPoint = postArea.selectionStart + tagprt1.length + selection.length;
		  /*insert tags around selection*/
		postArea.value = postArea.value.substring(0, postArea.selectionStart) + tagprt1 + selection + tagprt2 + postArea.value.substring(postArea.selectionEnd, postArea.value.length);
		range.select(insertPoint,insertPoint);
	}
}

 

postArea is declared according to the ID of text area sent. tagprt1 and 2 are both determined according to what the user clicked and are both strings of up to 10 characters in length.

 

The problem is almost definitely to do with determining the length of the selected text. No matter what is selected it returns zero for the alert. I have tried using 'value', 'innerHTML' and 'select' as well as 'text' to try determine the length.

 

If anyone knows what to do (or a more efficient way of doing this), please help.

 

Thank you

Joe

Link to comment
Share on other sites

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.