Tuesday, February 28, 2012

How to avoid removal of empty attributes for HTML elements in TinyMCE

TinyMCE has a habit of removing empty attributes for many HTML elements, and for various reasons this might not always be what you want.

For instance, today a customer ran into an issue where the value attribute of a <option> element was removed if it was empty. The empty value attribute was needed for custom validation purposes, so this caused quite a headache for them.

Another example which is more relevant for other projects, is the empty alt attribute for the <img> element, which is needed for the HTML to validate.

So how can you force TinyMCE to leave these empty attributes be instead of removing them? You can add your rule to extended_valid_elements, which will then be added to the default TinyMCE rule set.

Here’s the solution for allowing an empty value attribute for the <option> element:

extended_valid_elements: 'option[value=]'

And there’s the solution for allowing an empty alt attribute for the <img> element:

extended_valid_elements: 'img[alt=]'

Notice the equals (=) sign after the attribute name, this is what tells TinyMCE that an empty value is allowed. If you remove the equals (=) sign, for example option[value], TinyMCE would interpret the value attribute as being allowed for the option element, but it would still remove it if it contained an empty value.

I recommend having a look at the default rule set for TinyMCE if you’re not sure how TinyMCE treats the different elements and attributes!

4 comments:

  1. Ok it works, now marry my :)

    ReplyDelete
    Replies
    1. I'm glad I could help you out :) And what an offer in return!

      Delete
  2. This worked for me to. Thanks!!

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete