jQuery quickie: Reading the contents of form fields in an iframe

Mihai asks:

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.

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(document).ready(function() { }) </script> </head> <body> <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:

<form> <textarea id="content" cols="20" rows="20"> </textarea> </form>

So far so good. Now let's make that button actually do something. Here is what I added:

$("#testBtn").click(function() { var text = $("#testFrame").contents().find("#content").val(); console.log(text); });

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.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for Extend by Auth0. He focuses on serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com