04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 13: Scripting Forms<br />

var selection = frames[“richedit”].getSelection();<br />

//get selected text<br />

var selectedText = selection.toString();<br />

//get the range representing the selection<br />

var range = selection.getRangeAt(0);<br />

//highlight the selected text<br />

var span = frames[“richedit”].document.createElement(“span”);<br />

span.style.backgroundColor = “yellow”;<br />

range.surroundContents(span);<br />

This code places a yellow highlight around the selected text in a rich text editor. Using the DOM range in<br />

the default selection, the surroundContents() method surrounds the selection with a < span > element<br />

whose background color is yellow.<br />

IE doesn ’ t support DOM ranges, but it does allow interaction with the selected text via its own<br />

selection object. The selection object is a property of document , as discussed earlier in this chapter.<br />

To get the selected text in a rich text editor, you must first create a text range (discussed in Chapter 11 )<br />

and then use the text property as follows:<br />

var range = frames[“richedit”].document.selection.createRange();<br />

var selectedText = range.text;<br />

Performing HTML manipulations using IE text ranges is not as safe as using DOM ranges, but it is<br />

possible. To achieve the same highlighting effect as described using DOM ranges, you can use a<br />

combination of the htmlText property and the pasteHTML() method:<br />

var range = frames[“richedit”].document.selection.createRange();<br />

range.pasteHTML(“ < span style=\”background-color:yellow\” > ” + range.htmlText +<br />

“ < /span > ”);<br />

This code retrieves the HTML of the current selection using htmlText , and then surrounds it with a<br />

< span > and inserts it back into the selection using pasteHTML() .<br />

Rich Text in Forms<br />

Since rich text editing is implemented using an iframe instead of a form control, a rich text editor is<br />

technically not part of a form. That means the HTML will not be submitted to the server unless you<br />

extract the HTML manually and submit it yourself. This is typically done by having a hidden form field<br />

that is updated with the HTML from the iframe . Just before the form is submitted, the HTML is<br />

extracted from the iframe and inserted into the hidden field. For example, the following may be done in<br />

the form ’ s onsubmit event handler:<br />

EventUtil.addHandler(form, “submit”, function(event){<br />

event = EventUtil.getEvent(event);<br />

var target = EventUtil.getTarget(event);<br />

target.elements[“comments”].value = frames[“richedit”].document.body.innerHTML;<br />

});<br />

463

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!