Over in the SPServices Discussions, @PirateEric was having a problem setting the value of a Rich Text column (RTE) in a SharePoint form. He was referring to my blog post Finding the Contents of a SharePoint Rich Text Column with jQuery – And Changing It, which I’ll stand by, but the jQuery there wasn’t cutting it. (If you’d like to read the whole thread, it’s here.)
What Eric wanted to do was set the RTE when the form loaded based on the results of a call to GetListItems (the workhorse of the SharePoint Web Services operations). That call would grab an existing list item so that Eric could reuse some of the values.
In my earlier post, I was focused on changing the existing value in an RTE column. Eric wanted to populate an empty RTE column. (This method works to re-populate an RTE that already has a value as well.)
The code is actually far simpler in this case. To review, an RTE (which stands for Rich Text Editor) is a column like this:
The markup for the RTE in the DOM is (as you might expect) fairly complex, but here are the important bits. I’m showing a view of the markup for the entire table row which represents the RTE column in my SharePoint form.
Any existing value will be stored in the textarea I’ve highlighted, but also within the iframe I discussed in my prior post. To simply set the value of the RTE column, you can just insert your own markup – or simply text – into that textarea. SharePoint’s script will fire on that change event, populating the iframe contents appropriately.
The jQuery to do this is really simple:
var systemDescriptionRTETextArea = $("textarea[Title='System Description']"); alert($(systemDescriptionRTETextArea).html()); $(systemDescriptionRTETextArea).html("Cream cheese"); alert($(systemDescriptionRTETextArea).html());
Here’s what I’m doing here:
- Line 1: I’m finding the RTE’s textarea in the form using the selector. Many of the key elements in SharePoint forms have their title attribute set to the DisplayName of the column. (Unfortunately, this is not true of some columns types, like checkboxes and radio buttons, for example.)
- Line 2: I’m alerting the original contents of that textarea, just to see what’s already there (just for debugging)
- Line 3: I’m setting the value of the column to “Cream cheese”
- Line 4: I’m alerting the contents again to be sure that it “took”
There you go, simple jQuery to set the contents of an RTE column. Of course “Cream cheese” probably isn’t what you’re aiming for: you can insert any valid HTML.