I'm having trouble reading the contents of an iframe with jQuery. I have a Rich Text Editor (MceEdit) that dynamically generates an iframe that holds al the styled text until sumbit. Only then, it populates the textarea that gets POSTed to the server. What I want to do, is read the content of the iframe before submit, so I can send to the server via AJAX. (I'm trying to implement an autosave feature). I've already tried something like $('iframe').contents() or $('iframe').contents().html() but it doesn't work.
It looks like you were real close. The contents() method of jQuery is exactly what you want to use. The docs even specifically mention it being the one to use for iframes. Here is the demo I came up. I began without any code, just some simple html.
</head> <body> <input type="button" id="testBtn" value="Click to read"> <iframe src="test2.cfm" id="testFrame"></iframe>
}) </script> </head>
<input type="button" id="testBtn" value="Click to read">
<iframe src="test2.cfm" id="testFrame"></iframe> </body> </html>
Ok I lie - there is a bit of code - the document ready block, but it's not doing anything yet. Now let's look at test2.cfm:
<textarea id="content" cols="20" rows="20">
So far so good. Now let's make that button actually do something. Here is what I added:
var text = $("#testFrame").contents().find("#content").val();
So as I said, contents() was what you wanted. I just tie to that a find() command to get my textarea and then use a val() to get the value. If you want to try this, click the button below, and please note I make use of console. If your browser doesn't support console this demo will not work. It should be obvious that the concept still works cross platform if you remove the console call.