views:

179

answers:

3

This is a bit of a specific request unfortunately.

I have a CMS that allows a user to input text into a tinymce editor for various posts they have made. The editor is loaded via ajax to allow multiple posts to be edited from one page. I want to be able to check if there were edits made to the main text if cancel is clicked.

Currently I get the value of the text from the database during the ajax call, json_encode it, then store it in a javascript variable during the callback, to be checked against later. When cancel is clicked the current value of the hidden textarea (used by tinymce to store the data for submission) is grabbed using jquery.val() and checked against the stored value from the previous ajax call like this:

if(stored_value!=textarea.val())
{
    return true
}

It currently always returns true, even if no changes have been made.

The issue seems to be that the textarea.val() uses html entities, whereas the ajax jsoned version doesn't.

the response from ajax in firebug looks like this:

<p>some text<\/p>\r\n<p>some more text<\/p>

the textarea source code looks like this:

&lt;p&gt;some text&lt;/p&gt;
&lt;p&gt;some more text&lt;/p&gt;

these are obviously different, but how can I get them to be treated as the same when evaluated?

Is there a function that compares the final output of a string or a way to convert one string to the other using javascript?

I tried using html entities in the ajax page, but this returned the string with html entities intact when alerted, I assume because json_encoding it turned them into characters.

Any help would be greatly appreciated.

A: 

With prototype you just need to escape the Ajax response before compare it:

ajaxResponse.escapeHTML();

With JQuery I think is a little more different. Try this:

Escaping strings with Jquery

Rui Carneiro
thanks for the response, I'm not keen to use the prototype library as well as jquery, and the jquery solution doesn't seem work with .val() only .text() unfortunately.
andy-score
A: 

I really don't believe this is the best way with jQuery, but it works.

var test = "&lt;p&gt;some text&lt;/p&gt;";
var dummy = $("<p/>");
test = dummy.text(dummy.html(test));

alert(test);

Kind Regards

--Andy

jAndy
Internally, Prototype does something like that to do HTML escaping, so I don't think it's that bad.
Pointy
this seems to do the trick, thanks.
andy-score
A: 

Why dont you try a different approach?

Try to compare textarea.defaultValue and textarea.value before submit your form. If those values are equal the user did not changed anything.

Rui Carneiro
I may give this a go, as it seems like the most logical way of doing things, I remember reading about the defaultValue attribute (if it is an attribute) but haven't used it before.
andy-score