tags:

views:

56

answers:

1

I'm having some difficulties getting the script below to work with my text editor. I'm not sure what is wrong but selectionStart and selectionEnd are returning as undefined.

Its suppose to get highlighted text in an editable iframe and then replace it.

 var textarea = document.getElementById('editor').contentWindow.document.body.innerHTML;

 if (document.selection)
 {
  textarea.focus();
  var sel = document.selection.createRange();
  alert(sel.text);
  sel.text = '<b>' + sel.text + '</b>';
 } else {
  var len = textarea.length;
  alert(len);
  var start = textarea.selectionStart;
  alert(start);
  var end = textarea.selectionEnd;
  alert(end);
  var sel = textarea.substring(start, end);
  alert(sel);
  var replaced = '<b>' + sel + '<b>';
  textarea =  textarea.substring(0,start) + replaced + textarea.substring(end,len);
 }
+1  A: 

The reason selectionStart and selectionEnd are undefined is that your textarea variable contains a string, not a reference to a <textarea> element. You seem to be aware of this since elsewhere you're calling string methods such as substring. Just to be clear, strings have no selectionStart and selectionEnd properties; the objects that do are textareas and text inputs.

Tim Down
Thanks Tim. How would I modify it to work without a string?
Cory
It's unclear what your intention is. From your other questions and from the first line of your code in this one, it seems you're working on an iframe-based WYSIWYG editor. A textarea is something different: it's a text-only form control, such as what's used to add comments in Stack Overflow. If you're working with an actual textarea then you can use its `selectionStart` and `selectionEnd` properties (except in IE, but that's another story). If you're working with an editable iframe, you will need to use its Selection object.
Tim Down
I see... Was afraid that may be the case. How would I use the iframes Selection object? Appreciate your help.
Cory
It's unfortunately different between IE and other browsers. I'd suggest that if you're just starting with JavaScript, you may be taking on a little too much to try and write a WYSIWYG editor at this stage: there are different APIs and many quirks and browser differences to deal with. Start with reading the docs on the various APIs. MDC is good resource, and MSDN has documentation for the IE stuff. There are some links in my answer here: http://stackoverflow.com/questions/3527262/inserting-tags-wysiwyg-javascript-editor/3529323#3529323
Tim Down