'JQuery : check if TinyMCE contains string

Sorry for the long post, I tried to keep it as short and clear as possible. I'm sure the solution is fairly simple though.

I have a table :

<table>
 <tr>
  <td class="title">John</td>
  <td class="content"><p>John is a nice guy</p></td>
 </tr>
 <tr>
  <td class="title">Mary</td>
  <td class="content"><p>Mary is a nice girl</p></td>
 </tr>
</table>

When clicking on a cell of the 1st column, I want the content of the 2nd column to be added to a TinyMCE visual editor. So I added the following code, which works perfectly :

$("td.title").on("click", function () {
var thisRow = $(this).parents("tr");
var columnContent = $(thisRow).find(".content").html();
var tinyID = $(".acf-field-61dc2a9a0fefd").find("textarea").attr("id");
var tinyField = tinyMCE.editors[tinyID];
var tinyContent = tinyField.getContent(); 

tinyField.setContent(columnContent);
});

Now, when clicking again on the 1st column, I want the content of the 2nd column to be removed from tinyMCE (if it exists and hasn't been modified of course) - that way the 1st column works like a toggle button. So I modified the function :

if ( tinyContent.indexOf(columnContent) > -1 ) {
tinyField.setContent('');
}

else {
tinyField.setContent(columnContent);
} 

However, there is absolutely no way to make this work. It adds the content, no problem, but it doesn't remove it after clicking again.

If i replace

if ( tinyContent.indexOf(columnContent) > -1 ) {

by

if ( tinyContent.indexOf('John is a nice guy') > -1 ) {

it will work just fine. Clicking on John will add "John is a nice guy" in the tinyMCE, and clicking again on John will remove "John is a nice guy".

My intuition was that it has something to do with the content format (html or text), so I tried modifying the variables, for example :

var columnContent = $(thisRow).find(".content").text();
var tinyContent = tinyField.getContent({format: 'text'}); 

I tried many combinations, but no success. It really frustrates me because the function worked fine when the field was a textarea instead of a TinyMCE.

Thank you in advance for any input you might have



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source