I need to show for every link, dynamically some text with Java-Script (jQuery). The problem is that the text is also formatted as HTML, so this causes some problems in the later view. Now I am storing it in the ID-attribute, this works, but only without embedded HTML in it.
<?php
...
$desc = '<p style="color: red">some <span>data</span></p>';
echo '<a href="#" id="' . $desc . '">' . $key . '</a>';
?>
Ajax-requests are not allowed. Is there a simple way to reach this goal?
The id
attribute is one of the least appropriate places for this (must be unique, cannot contain all characters). Use a data-
attribute (introduced in HTML5 but also works in old browsers and without using a HTML5 doctype) instead:
<a href="#" data-desc="....">
If you are using jQuery you can access it via .data('desc')
, in plain JavaScript the most portable way is using .getAttribute('data-desc')
. If you do not need to support older browsers, you can access the value via the .dataset.desc
property.
In any case, you need to ensure that nothing breaks when inserting dynamic data in the attribute. Use htmlspecialchars()
for this purpose:
$desc = '<p style="color: red">some <span>data</span></p>';
echo '<a href="#" data-desc="' . htmlspecialchars($desc) . '">' . $key . '</a>';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With