Yaz's Blog

I am a (php+ruby+js+css+) developer. I am a geek. I am a fiction reader. A movie and tv addict.
An XBOX360 player. A snowboarder. A cyclist. A Softball player. A Venezuelan-Canadian.

[tech] CodeMirror: getting value of a textarea loaded with ajax.

The setup is like this, I have a textarea on a form that gets loaded through ajax. After the request has finished, CodeMirror turns that textarea into a nice editable field for css code.

The issue was, once I try to save the form (also with ajax), I couldn’t get the value of the field to send it along with the rest of the request because the instance of CodeMirror wasn’t in the scope of the second function (SaveForm).

So, after posting in the CodeMirror Google Groups, I got some guidance, and this is the end -functional- result.

// 
// HTML - loaded with ajax thru LoadForm()
//

<form name="TheForm" id="TheForm" onsubmit="return false;">
<textarea id="css_code" name="css_code">
<? echo $strCssCodeFromDatabase ?>
</textarea>

<input type="button" onclick="SaveForm()" value="Save">
</form>

//
// In the JS file
//

// Setup variable for later use
var cssEditorHandle;

function LoadForm() {
// prototype ajax updater
new Ajax.Updater('form_div', 'url.php', {
onComplete: function(transport) {

// create CodeMirror instance (without the 'var')
cssEditorHandle = new CodeMirror.fromTextArea("css_code", {
parserfile: "parsecss.js",
path: "/codemirror/",
stylesheet: "/codemirror/css/csscolors.css",
});
}
});
}

function SaveForm() {
// assign the code to the textarea
// that was hidden with CodeMirror.fromTextArea() )
$('css_code').value = cssEditorHandle.getCode() ;

// serialize form values
var Parameters = "action=SaveForm&" + Form.serialize($('TheForm'));

// send prototype ajax request to save everything
new Ajax.Request('/url.php', { parameters : Parameters });
}

Blog comments powered by Disqus