Javascript syntax - triple quotes in a single line - javascript

Following my code:
<div onclick="this.innerHTML='<div onclick=\"<img src=/*how to do here?*//>\">abc</div>'">a</div>
I would like to do everything on one line, can I specify the address of the image with the current example code or not?

Use " to represent a " character in an HTML attribute value delimited with " characters.
(Use & to represent a & character in an HTML attribute value, so if you want to nest insanely then: &quot;)
But don't do this.
Writing everything on a single line in not a virtue.
Writing JS in an onclick attribute instead of a .js file is not a good thing.
Use addEventListener and friends.

Related

ENT_QUOTES in a JS string

I have this function :
function change_this(my_str)
{
$('#myDiv').html('<input value=\''+my_str+'\'>');
}
When I call this function with this :
onclick=change_this('Test '');
I see in the debugger that ' has been turned to a quote, and therefore the script does not work.
So my question is: how can I send a quote inside a string to a JS function?
I'm sure I'm not the first person to face this issue, I googled but did not find any simple explanations / answers.
You have two problems. This is because you have HTML embedded in JavaScript embedded in HTML which you are then generating HTML from by mashing together strings of JavaScript. You switch languages so many often it makes my head spin.
Problem 1: Getting the right string into the function
To include a single quote inside a string delimited by single quotes in JavaScript, you must escape them with a \.
onclick="change_this('Test \'');"
There is no need to use character references here. There are no ' with special meaning in the HTML. You would need to use ' three times if you had used ' instead of " to delimit the attribute value.
I'd avoid onclick entirely and favour data- attributes and JS event binding.
<input type="button" data-foo="Test '">
$("[type=button]").on('click', function (event) {
change_this( $(this).data('foo') );
});
Problem 2: Getting the right string into the HTML attribute value.
With the approach you are taking, you would need to convert the ' to '. Note that you would have to do it programatically because if you had it in the onclick attribute then it would be converted to ' by the HTML parser before the JavaScript engine even saw it.
Don't use your current approach though. Mashing strings together to make HTML is a nightmare.
Use DOM or something jQuery that vaguely resembles DOM.
var input = $("<input />").val(my_str);
$('#myDiv').empty().append(input);

unescape in javascript not working when %26 ( & sign) is in value

I have the below code in my JSP. UI displays every character correctly other than "&".
<c:out value="<script>var escapedData=unescape('${column}');
$('div').html(escapedData);</script>" escapeXml="false" /> </div>
E.g. 1) working case
input = ni!er#
Value in my escapedData variable is ni%21er%40. Now when I put it in my div using
$('div').html(escapedData); then o/p on html is as expected
E.g. 2) Issue case
input = nice&
Value in my escapedData variable is nice%26. Now when I put it in my div using
$('div').html(escapedData); then also it displays below
$('#test20').html('nice%26');
However, when output is displayed in JSP, it just prints "nice". It truncates everything after &.
Any suggestions?
It looks like you have some misunderstandings what unescape(val)/escape(val) do and where you need them. And what you need to take attention of when you use .html().
HTML and URI have certain character that have special meanings. The most important ones are:
HTML: <, >, &
URI: /,?,%,&
If you want to use one of those characters in HTML or URI you need to escape them.
The escaping for URI and for HTML are different.
The functions unescape/escape (deprecated) and decodeURI/endcodeURI are for URI. But was you want is to escape your data into the HTML format.
There is no build-in function in_JS_ that does this but you could e.g. use the code of the answer to this question Can I escape html special chars in javascript?.
But as it seems that you use jQuery you could think of just using .text instead of .html as this will do the escaping for you.
An additional note:
I'm pretty sure that the var escapedData=unescape('${column}'); does not do anything. I assume that ${column} already is ni!er#/nice&.
So please check your source code. If var escapedData=unescape('${column}'); will look like var escapedData=unescape('ni!er#'); then you should remove the unescape otherwise you would not get the expected result if the ${column} contains something like e.g. %23.

How to decode html miscellaneous symbol from its glyph?

I have a div that contains a settings icon that is a html miscellaneous symbol
<span class="settings-icon">⚙</span>
I have a jasmine test that checks the div contents to makes sure that it is not changed.
it("the settings div should contain ⚙", function() {
var settingsIconDiv = $('.settings-icon');
expect(settingsIconDiv.text())
.toContain('⚙');
});
It will not pass as it is evaluated as its glyph symbol of a gear icon ⚙
How to I decode the glyph in order to pass the test?
To get actual character from Unicode to compare it to a literal in HTML you can use String.fromCharCode() e.g.
.toContain(String.fromCharCode(9881))
You should check against the string '⚙' or, if you do not how to enter it in your code, the escape notation \u2699. There are other, clumsier ways to construct a string containing the character, but simplicity is best.
No matter how the character is written in HTML source code (e.g., as the reference ⚙), it appears in the DOM as the character itself, U+2699. In JavaScript, a string like ⚙ is just a sequence of seven Ascii characters (though you can pass it to a function that parses it as an HTML character reference, or you can assign it e.g. to the innerHTML property, causing HTML parsing, but this is rather pointless and confusing).
To match the browser behavior (because you don't know how it is encoded in html or in text) i would try the following
.toContain($("<span>⚙</span>").text()) instead of .toContain('⚙').
That way it should match how it is stored in the dom.
The String.fromCharCode(9881); mentioned by Yuriy Galanter will definitely also work reliable. But because dom engine and the js engine are two different parts, that could behave differently, i would test with both techniques.

jQuery URI encode (char &) .html() attribute value

I've read a lot of the HTML encoding post for the last day to solve this. I just managed to locate it.
Basicly I have set an attribute on an embed tag with jQuery. It all works fine in the browser.
No I want to read the HTML itself to add the result as a value for an input field to let the user copy & past it.
The PROBLEM is that the .html() function (also plain JS .innerHTML) converts the '&' char into '& amp;' (without the space). Using differen html encoder functions doesnt make a difference. I need the '&' char in the embed code.
Here is the code:
HTML:
<div id="preview_small">
<object><embed src="main.swf?XY=xyz&YXX=xyzz"></embed>
</object></div>
jQuery:
$("#preview_small object").clone().html();
returns
... src=main.swf?XY=xyz&YXX=xyzz ...
When I use:
$("#preview_small object").clone().children("embed").attr("src");
returns
main.swf?XY=xyz&YXX=xyzz
Any ideas how I can get the '&' char direct, without using regex after I got the string with .html()
I need the & char in the embed code.
No you don't. This:
<embed src="xyz&YXX=xyz"></embed>
is invalid HTML. It'll work in browsers since they try to fix up mistakes like this, but only as long as the string YXX doesn't happen to match an HTML entity name. You don't want to rely on that.
This:
<embed src="xyz&YXX=xyz"></embed>
is correct, works everywhere, and is the version you should be telling your users to copy and paste.
attr("src") returns xyz&YXX=xyz
Yes, that's the underlying value of that attribute. Attribute values and text content can contain almost any character directly. It's only the HTML serialisation of them where they have to be encoded:
<div title="a<b"&c>d">
$('div').attr('title') -> a<b"&c>d
I want to read the HTML itself to add the result as a value for an input field
<textarea id="foo"></textarea>
$('#foo').val($('#preview_small object').html());
However note that the serialised output of innerHTML/html() is not in any particular fixed dialect of HTML, and in particular IE may give you code that, though generally understandable by browsers, is also not technically valid:
$('#somediv').html('<div title="a/b"></div>');
$('#somediv').html() -> '<DIV title=a/b></DIV>' - missing quotes
So if you know the particular format of HTML you want to present to the user, you may be better off generating it yourself:
function encodeHTML(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}
var src= 'XY=xyz&YXX=xyzz';
$('#foo').val('<embed src="'+encodeHTML(src)+'"><\/embed>');
(The \/ in the close tag is just so that doesn't get mistaken as the end of a <script> block, in case you're in one.)

IE innerHTML chops sentence if the last word contains '&' (ampersand)

I am trying to populate a DOM element with ID 'myElement'. The content which I'm populating is a mix of text and HTML elements.
Assume following is the content I wish to populate in my DOM element.
var x = "<b>Success</b> is a matter of hard work &luck";
I tried using innerHTML as follows,
document.getElementById("myElement").innerHTML=x;
This resulted in chopping off of the last word in my sentence.
Apparently, the problem is due to the '&' character present in the last word. I played around with the '&' and innerHTML and following are my observations.
If the last word of the content is less than 10 characters and if it has a '&' character present in it, innerHTML chops off the sentence at '&'.
This problem does not happen in firefox.
If I use innerText the last word is in tact but then all the HTML tags which are part of the content becomes plain text.
I tried populating through jQuery's #html method,
$("#myElement").html(x);
This approach solves the problem in IE but not in chrome.
How can I insert a HTML content with a last word containing '&' without it being chopped off in all browsers?
Update : 1. I tried html encoding the content which I am trying to insert into the DOM. When I encode the content, the html tags which are part of the content becomes plain string.
For the above mentioned content, I expect the result to be rendered as,
Success is a matter of hard work &luck
but when I encode what I actually get in the rendered page is,
<b>Success</b> is a matter of hard work &luck
You should replace your & with &.
The & (ampersand) character is used within HTML to represent various special characters. For example, " = ", < = <, etcetera. Now, &luck clearly is not a valid HTML entity (for one it is missing the semicolon). However, various browsers may, due to combinations of error correcting (the semicolon), and the fact that it looks somewhat like an HTML entity (& followed by four characters) try to parse it as such.
Because &luck; is not a valid HTML entity, the original text is lost. Because of this, when using an ampersand in your HTML, always use &.
Update: When this text is entered by a user, it is up to you to escape this character properly. In PHP for example, you would call htmlentities on the text before displaying it to the user. This has the added benefit of filtering out malicious user code such as <script> tags.
The ampersand is a special character in HTML that indicates the start of a character entity reference or numeric character reference, you need to escape it like so:
var x = "<b>Success</b> is a matter of hard work &luck";
Try using this instead:
var x = "<b>Success</b> is a matter of hard work &luck";
By HTML encoding the ampersand, you are ensuring that there is no ambiguity in what you mean when you write "&luck".

Categories