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
https://forums.phpfreaks.com/topic/240318-length-of-a-range-in-ie/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.