How do I encode html for Bootstrap popover and tooltip content - javascript

This may be a duplicate; it's hard to tell because the key words contain "html" and "content" and even Bing and Google were returning a lot of false positives.
Bootstrap tooltips and popovers support html values for the data-content attribute when data-html=true. However, this isn't valid
<input id="email" class="form-control" type="email"
data-bind="value: Email, valueUpdate: 'afterkeydown'"
data-container="body" data-toggle="popover" data-placement="bottom"
data-title="Email" data-html="true"
data-content="<p>This is <i>your</i> email address.</p>" />
because you can't just put html in the value of an attribute that is itself HTML. It may confuse the parser and is not permitted by the HTML specification.
While it seems to work with Internet Explorer, I really don't feel like testing with fifty different browsers and versions. It certainly does confuse the parser in the Visual Studio 2013 HTML editor. That editor thinks there's no closing quote.
I could dodge this by assigning the attribute from JavaScript in a separate file, but that's clumsy and defeats the separation of concerns.
So, what's the right way to mark this up?

As the accepted answer points out, you can't have a quote " inside a string quoted with ". This problem occurs often. If you want to display text that looks like HTML, then how is the browser supposed to know what it should parse as HTML and what it should simply display.
For example, how do you get a browser to display the text <p></p>
The answer is escaping. Instead of characters like " and <, you use placeholders like " and <
However, the solution of escaping the quotes doesn't work here. Precisely because the browser will not parse it as HTML. If you put escaped quotes in your html, they don't look like quotes to the browser, they look like text.
There is a different solution however: A string that is quoted with " can contain ' without problems. The following is valid:
data-content="<div id='string_in_string' ></div>"
This can be applied to your bootstrap popovers, I've set up a fiddle, it shows how the single quote strings are correctly parsed, while the escaped strings confuse the browser: https://jsfiddle.net/z4t2sud3/3/
This is the code inside the fiddle (the fiddle environment automatically imports bootstrap, jquery, etc)
<mark data-content="
<button class="btnr" type="button">
Doesn't work
</button>
<button class='btn btn-info' type='button'>
Works
</button>
" data-html="true" data-toggle="popover">
Popovered
</mark>
And be sure to activate the popover via Javascript:
$(function () {
$('[data-toggle="popover"]').popover()
})

You can add whatever you want to an HTML attribute as long as it is a valid html attribute value. What is a valid attribute value? What does not contains tags, quotes and so on. So.... and what? The solution is: Scape the string before append it inside the html attribute.
If you are using PHP: http://fi2.php.net/htmlspecialchars
Or Twig: http://twig.sensiolabs.org/doc/filters/escape.html
If you are using jquery, when you do $el.data('my_scaped_json) will be converted to whatever it was originally, such a json object or html-string: $( $el.data('my_scaped_html) );

Related

special character is not coming in alert box as it it

I have one code
<input type="button" id="btnGetText" value="Get Text"/>
<div id="myDiv">
<p>First Lineα and text.</p>
<p>Second Line <b>Bolded</b></p>
</div>
If I am alerting the html of #myDiv is coming in alert but &alpha not coming.
If I am alerting &alpha its giving α
here is the fiddle attached
http://jsfiddle.net/getyoursuresh/hv2ed/
You are not alerting the original HTML. You are alerting a serialization of the DOM to HTML.
α and α are equivalent in HTML, so either are perfectly valid when designing a serialization algorithm. HTML 5 describes the algorithm browsers are supposed to use.
As described in the section starting "Escaping a string", non-breaking spaces should be serialized to character references while alphas are not.
If you want to work with your original HTML then you'll need to use XMLHttpRequest to refetch the original document from the server and then parse the raw text of the response yourself.
Edited:
Alpha character can be used directly in html although it has an html encoding, unlike the unbreakable space which has to remain in html encoding even after processing it because that character only exists in html encoding.

Handling single quote in JavaScript and jQuery

I am trying to display values in a div of JSP dynamically. The below $('#test${i}${j}') selects a div dynamically as I want, but the HTML part is creating issue for me. ${column} is just a value, for example, accountant, financeMR, etc.:
<c:out value="<script>$('#test${i}${j}').html(${column}); </script>" escapeXml="false" />
In the above I get an error which says "accountant is undefined", etc. The reason being there is no single quote (') wrapping ${column} (in HTML). However, if I try the below, it works in all cases except the cases where the ${column} value contains a single quote. For example, Mng'r:
<c:out value="<script>$('#test${i}${j}').html('${column}'); </script>" escapeXml="false" />
How can I resolve it?
The Apache commons lang library provides escape utilities: http://commons.apache.org/proper/commons-lang/
This should do the trick:
StringEscapeUtils.escapeEcmaScript(inputString);

impossible to escape single quotes in XML

please help me with this issue. I have a php file which generates XML. I have the following code that I can not escape a JS script within XML as follows:
$xml_after='<html>'.htmlspecialchars('
<div class="options" id="options_'.$tables_row['id'].'">
<a class="insidetable" href="" title="'.$lang['delete'].'"
onClick="show_confirmation(\''.$messages['delete_table'].'\',\''.$lang['close'].'\',hide_element(\'confirmation\');\''.$lang['delete'].'\',remove_table(\''.$tables_row['id'].'\');hide_element(\'confirmation\');\');return false;\" ><img src="../images/interface/icons/delete.png" />
</a></div>').'</html>';
The problem is in onclick functions..
Please help, full day losted already , thank you
Be aware that htmlspecialchars() escapes < and >, too. You have to use it on each value separately, not on the complete html fragment.
htmlspecialchars() has an option that escapes all quotes.
var_dump(htmlspecialchars("Escaping: <>&'\"", ENT_QUOTES));
Ouptut:
string(35) "Escaping: <>&'""
But it would be better to use DOM and let it take care of the escaping.
Additionally, I suggest using data-* attributes in HTML. The Javascript can read the attributes and bind the logic to the elements. This separates the actual JS logic from the HTML.
I think your code is incorrectly formatted
$xml_after='<html>'.htmlspecialchars('<div class="options"
id="options_'.$tables_row['id'].'">
<a class="insidetable" href="" title="'.$lang['delete'].'"
onClick="
show_confirmation(\''.$messages['delete_table'].'\',\''.$lang['close'].'
\', hide_element(\'confirmation\');\''.$lang['delete'].'
\', remove_table(\''.$tables_row['id'].'\');
hide_element(\'confirmation
\');
\');return false;\" >
<img src="../images/interface/icons/delete.png" />
</a></div>').'</html>';
after each of the functions inside the show_confirmation functions you have a ; which isn't valid in a function calls parameter list
On the last line of the onClick function:
\');\');return false;\" >
The second \' is unmatched and the double quote \" shouldn't be escaped as far as I can see change that and maybe it will work for you.

Put JSON data into html form input hidden?

I'm building a rich web application that uses a lot of data. When I'm building it I found that I was repeating myself over and over.
This is the problem. I need to put hidden application logic into HTML elements to represent the data being viewed by the client.
This is a solution I found some time ago:
<a href="bla" data-itemId="1" .... more data.
There are two problems with this method.
I can't represent arrays.
It's just ugly.
I searched for a solution but did not find anything. I also went to facebook, opened firebug,
and found this:
{"actor":"19034719952","target_fbid":"454811929952","target_profile_id":"19034719952","type_id":"7","source":"1","assoc_obj_id":"","source_app_id":"","extra_story_params":[],"content_timestamp":"1324385453","check_hash":"9eabc3553e8a2fb6"}
This json was inside an input[type=hidden] element.
I tried to do the same thing with json_encode();
<input type="hidden" name="track" value="{"_id":{"$id":"4eee908f615c2102e9010000"},"link":"george-wassouf-flag-of-my-heart-longing","file":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","lyrics":null,"freezed":false,"hits":0,"images":{"large":"\/assets\/static\/default.track.large.jpg","thumb":"\/assets\/static\/default.track.thumb.jpg","icon":"\/assets\/static\/default.track.icon.jpg"},"duration":"300","created":{"sec":1324257423,"usec":78000},"albums":[{"_id":{"$id":"4eee8d63615c21f6e7000000"},"names":{"ar":"\u0643\u0644\u0627\u0645\u0643 \u064a\u0627 \u062d\u0628\u064a\u0628\u064a","en":"Kalamak ya Habibi"},"link":"george-wassouf-kalamak-ya-habibi","images":{"original":"\/m\/pics\/albums\/o.4eee8d612c3183.11879972.jpg","poster":"\/m\/pics\/albums\/p.4eee8d63967072.02645896.jpg","large":"\/m\/pics\/albums\/l.4eee8d63a89111.20372767.jpg","small":"\/m\/pics\/albums\/s.4eee8d63b18927.47242533.jpg","thumb":"\/m\/pics\/albums\/t.4eee8d63b7f1f4.11879932.jpg","icon":"\/m\/pics\/albums\/i.4eee8d63bf1304.59902753.jpg"}},{"_id":{"$id":"4eee8d63615c21f6e7000000"},"name":"Kalamak ya Habibi","link":"george-wassouf-kalamak-ya-habibi"}],"name":"Flag of my heart longing","title":"Flag of my heart longing","mp3":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","poster":"\/m\/pics\/artists\/p.4eee85cd7ed579.65275366.jpg","artists":[{"_id":{"$id":"4eee85cd615c21ece6000000"},"name":"George Wassouf","link":"george-wassouf"}]}" />
But when I try getting the value I get this {.
I have tried all constants like JSON_HEX_TAG and did not find any questions of this type.
How can I put JSON into HTML correctly and then get it with jquery/javascript?
Your string is correct, but it cannot be defined in HTML because it contains double quotes.
HTML requires you to escape double quotes when you are defining a String that is itself enclosed within double quotes. The appropriate way of doing this is using the HTML entity:
value="""
From PHP:
Use htmlspecialchars or htmlentities (http://www.php.net/manual/en/function.htmlspecialchars.php). In any case, you normally should be using this over EVERY value you write to the client browser (not doing so may result in security risks).
From Javascript:
If you need to do this from Javascript, you can programatically set the value of the hidden element (provided your JSON string is already contained in a Javascript variable). This way you don't have to worry about encoding the string literal:
hiddenElement.value = yourString;
In order to get an escape function you can use, maybe check this thread: Escaping HTML strings with jQuery .
Best way for me was to use html & quot;
for example i do this:
<input type="hidden" id="v" value="[{"id":"1"}]" >
instead of
<input type="hidden" id="v" value="[{"id":"1"}]" >
in your input tag, the value attribute in which you are trying to put json array. Look at it. you are putting ". Second " is ending the attribute value. thus it is being interpreted as value = "{". you need to escape those ". Use single quotes ' instead. And check then
It seems my answer is late, but I want to contribute to those who come later.
Before coming here you have the concept of HTML.Use single quotes ' , Should not do that, although it still works, it is against the HTML principle .
The best way is: Use htmlspecialchars or htmlentities. #jjmont said above.
I have a small example:
<input id="jsondata" value="<?php echo htmlspecialchars( json_encode($data), ENT_COMPAT ); ?>" >
||
<input id="jsondata" value="<?php echo htmlspecialchars( json_encode($data), ENT_NOQUOTES ); ?>" >
php
set array in
<input type="checkbox" name="deviceInfo" value="<?php print_r(json_encode(array_filter($array_data), JSON_FORCE_OBJECT));?>" />
?>

Javascript InnerHTML in IE7 messing with INPUT tags

When I receive the innerHTML of an element containing an input[type=text] element the speech marks around the value and id are removed in IE7 i.e.
<input type="text" id="test" value="test" />
Becomes:
<input type="text" id=test value=test />
This would be fine, other than the fact that I am using a JQuery plugin that takes a html segment and binds JSON to it. This means if I have a template:
<div id="template"><input type="text" value="${ValueToBind}" /></div>
When I retrieve this via document.getElementByID("template").innerHTML i get:
<input type="text" value=${ValueToBind} />
Thus, if I am binding a string with whitespace i.e. "this is a test" the output is:
<input type="text" value=this is a test />
Obviously, this is invalid html and causing havoc with my app. What I really need to do it to retrieve the html in the template AS IS, and not have IE try to do anything helpful like remove the " speech marks.
Cheers, Chris.
answered here innerHTML removes attribute quotes in Internet Explorer
If the problem is IE7 specific a quick fix may be to add an IE conditional comment for IE7 with code that re-inserts the quote marks.
I believe this isn't something you can get around directly as the quotemark-less html is just how IE7 represents the DOM node internally.
My view on the best way to ensure you get the exactly right template is to read each attribute of each node yourself rather than the inner html and then write them out with the quote marks.
See
innerHTML removes attribute quotes in Internet Explorer
for other ideas.
Using jQuery's .html()
http://docs.jquery.com/Attributes/html
would generally be the "jQuery way" to do this also rather than .getElementById

Categories