Escaping HTML special character with JSP or JQuery - javascript

My JSP file contains a table with the following row:
<td class="description" id="${doc.id}"></td>
I want it to be empty at first, as above. Later, after the page is loaded and some logic is processed, I want to fill it asynchronously with a content using JQuery .html method:
$("#${doc.id}").html("${doc.description}");
For regular user inputs everything works fine, but error occurs, when a user enters special character: "
How can I prevent application from reading that character as special, and have the application running correctly?
I have tried to use JSP escape functions like this:
$("#${doc.id}").html("${fn:escapeXml(doc.description)}");
And this:
$("#${doc.id}").html("<c:out value="${doc.description}"/>");
And neither first nor second worked. Why?

Here is one way - seeing you already have the data on the page
<td class="description hide" id="${doc.id}"><c:out value="${doc.description}"/></td>
where
.hide is {display:none}
and then
$("#${doc.id}").show();

Related

My ID's have been changed, how can i stop it?

I've been trying to do something simple, i think, let me explain:
I have an BPMS software where a send an e-mail at the end of the process, this e-mail is an HTML page that i created, inside the HTML page we have some identifying codes that get a field value from an previously form, some strings. The problem is, when i transfer that value to the HTML page, obviously the "Enter" key doesn't work like the "br" tag, so i made a simple javascript to replace the "enter" for the "br". It worked, but when i send the e-mail my ID is changed and they put an "x_" prefix, so there goes my question.
Can i stop it or there is some other way to do it?
The code is below:
<p id="informacoes">
TEST
TEST
</p>
<script>
var strMessege = document.getElementById('informacoes');
strMessege.innerHTML = strMessege.innerHTML.replace(/(?:\r\n|\r|\n)/g, '<br />');
</script>
It seems like your end goal here is to retain original line breaks present in the source code. I think your best bet would be to address this using CSS.
Take a look at the CSS property white-space, MDN: white-space property
By default, CSS collapses white space (e.g. multiple non-breaking ("regular") spaces, tabs, and newlines) into, effectively, a single regular space. In your example, the line breaks that you see in the source code are being collapsed and so they will not be rendered by the browser or email client.
Try using CSS to set a different white-space property, like
#informacoes {
white-space: pre-line;
/* depending on your use case,
a different value might work better */
}
Property values other than white-space: normal (which is the default) will change whether and how white space, including new lines, are collapsed when rendering from the source code to the screen.

Handling multi-line HTML inside Javascript

I am using Javascript to define a button behaviour on a web page. The behaviour I am after is to insert some new HTML somewhere on my page, but I would like to use the MVC extension method Html.EditorFor to define the new HTML which will be inserted.
What I would like to do is the following:
$("#myButton").click(function() {
$("#(Html.EditorFor(x => x.SomeModelProperty))").insertBefore(<somewhere>);
});
The problem I'm encountering is that the MvcHtmlString returned by the call to EditorFor renders as multi-line HTML, resulting in invalid Javascript:
$("<div>
<label for="ModelData_SomeModelProperty">SomeModelProperty</label>
</div>
<div> ....
In an ideal world, I could get EditorFor to somehow render all of the above on a single line, or use some kind of special Javascript syntax to define a multi-line string (like using single quotes in C#), but so far I'm drawing a blank.
I've tried calling ToHtmlString and hand-editing the resulting string to remove line-breaks, and I'm aware that I can escape the new lines in Javascript using a /, but the problem with doing so is that I then have to handle the escaped HTML, which looks a little like the following:
$("<div>
<label for="ModelData_SomeModelProperty">SomeModelProperty</label>
</div>
<div> .... (you get the idea)
I was just wondering whether anyone had tried anything similar and might have a more elegant approach?
One way would be to get it written into a hidden div in html instead of directly into the javascript. Then you can just read it from the dom to use in you script.
So you page would have a
<div style="display:none" id="hiddenArea">
...insert whatever you want in here
with newline or whatever...
</div>
And then in your javascript:
$("#myButton").click(function() {
var source = $("#hiddenArea").html();
$(source).insertBefore(<somewhere>);
});
You could maybe create a HTML helper so you much more control on what's returned and how it is formatted.
http://www.codeproject.com/Tips/720515/Custom-HTML-Helper-for-MVC-Application

Exporting specific part of a html page with batch

Firstly I'm new to the community as an user, and I want to say it is a great one.
My question is that I want to get an URL from an <a href="" element, using <alt="new"> or the name of an image used in that <td> part from a webpage that changes daily and doesn't belong to me.
So far I've coded something to download the page with wget to a text file, then searched for the image or alt variable. Even if it brought me the part that the searched items existed, it doesn't include the <a href part I needed that's located just before the image.
edit: i managed to get the line below, i just need to get the url inside with batch, or redirect to it with javascript, but since title and url changes, it was challenging. Any help ?
<td width="150" align="left" valign="top"><b><u>"SOMETEXT"</u></b>
Using your provided code:
set "x=<td width="150" align="left" valign="top"><b><u>"SOMETEXT"</u></b>"
set "x=%x:<=%" & :: Remove Redirection Character
set "x=%x:>=%" & :: Remove Redirection Character
set x=%x:*href=% & :: Remove everything up till href=
set x=%x:~2% & :: Trim ="
set x=%x:"='% & :: Replace Double Quotes with Single Quotes
set "x=%x:' =" & rem % & :: Remove everything after URL
echo %x%
Notice the double quotes, they are essential for removing the html tag deliminators < and >, because those are redirection characters, which will cause errors unless surounded by double quotes.
You can copy and paste the above code directly into the command prompt to test it.
If I understand you corectly you want do get from HTML file link contained in <a href="" ?
first solution that comes to my mind is to download entire HTML and use python and BeautifulSoup library to parse this file and get all 'hrefs'. Is that what you mean?

Javascript doesn't recognise items entered into DIV Using XMLHttpRequest

Having searched the site, I think the issue I'm having may relate to using innerHTML to populate a <div> but I can't quite find a solution that I can map onto my specific issue. Hope someone can help. Basically, I have an HTML page that contains a form with a text field. The page also contains an empty <div> which will be populated with a table-of-contents in a moment. The <div> is defined as:
<div id="toc_menu" class="menu_list">
I've set the onkeyup attribute of the form text field to run a Javascript function (defined in the HTML <head>) which defines a XMLHttpRequest and sends the value entered in the text input field (str) to a PHP page using xmlhttp.open("GET","toc_items.php?filter="+str,true). The PHP page GETS the value of 'filter' and runs a MySQL query. It then produces some results which are echoed back to the empty as a table-of-contents with main headings and subheadings using:
document.getElementById("toc_menu").innerHTML=xmlhttp.responseText;
This works more-or-less as expected. The length of the returned table-of-contents changes as text is entered into the text field. There is, however, a problem. This table-of-contents is supposed to have an accordion effect created using a script which is defined in the HTML <head>. The script was developed by Roshan Bhattarai and works beautifully when the table-of-contents list is hard-coded into the HTML page. The script is as follows:
<script type="text/javascript">
<!--
//---------------------------------+
// Developed by Roshan Bhattarai
// Visit http://roshanbh.com.np for this script and more.
// This notice MUST stay intact for legal use
// --------------------------------->
$(document).ready(function()
{
//slides the element with class "menu_body" when paragraph with class "menu_head" is clicked
$("#toc_menu p.menu_head").click(function()
{
$(this).css({backgroundImage:"url(down.png)"}).next("div.menu_body").slideToggle(300).siblings("div.menu_body").slideUp("slow");
$(this).siblings().css({backgroundImage:"url(left.png)"});
});
});
</script>
The table-of-contents items that are formatted as follows:
<p class="menu_head">HEADING</p>;
<div class="menu_body">;
SubHeading';
</div>;
It appears that the table-of-contents items that are inserted into the <div> don't trigger the Javascript in the HTML page <head> (although the text is formatted correctly using CSS files also defined in <head>). I can manually copy the output from the PHP page and paste it into the <div> and the accordion effect works perfectly.
Any suggestions would be greatly appreciated.
It appears that the code block:
<p class="menu_head">HEADING</p>;
<div class="menu_body">;
SubHeading';
</div>;
is echoed back by PHP from the ajax call. Correct me if I'm wrong on that. If the ajax call builds this html and echos it to the screen, the above script will not work. The ajax call is made via the keyup event on the form as you stated above. However, the script above is run on
$(document).ready. If what I'm understanding is true, the content is placed in the innerhtml of the div when the ajax call is made not when the page loads. Because there are no "p" elements with the class "menu_head" when the page loads on $(document).ready, jquery cannot bind the .click event properly. The script needs to be executed after the ajax call returns and the DOM has been updated with the new elements.
In other words on successful return from the ajax call, run the above script, not on $(document).ready. Once the elements are in the DOM, jquery can find them and bind to them the .click event. The script execution should then complete successfully.
Hope this helps.
I haven't studied your code in detail, but did notice your empty div element has no close tag (unless you've omitted this detail). You should always have a close tag (for div elements) to ensure the DOM doesn't make an invalid assumption as to where this should be inserted, use:
<div id="toc_menu" class="menu_list"></div>

Passing apostrophe to javascript function

I am not finding a solution on this one using JavaScript (to utilize localStorage) in a JSP.
Trying to pass something with apostrophe. I have done a .replaceAll() and replaced the ' with ' and it still passes it as an '.
I have also tried a .split("'") and replaced the apostrophe with:
(\' , ' , \', '' , ''' and '\'')
All of these just pass an apostrophe to the function (what I see when I hover over the link) like this:
Save job
With a and b being the two split substrings but with no effect. I do notice that spaces are converted into %20, but that's little comfort. Any other ideas?
Your JSP code is irrelevant. Decide what HTML you want to produce and produce it.
The following are all valid HTML markup:
<a href="saveJob('Bob\'s Question')"> …
<a href="saveJob("Bob&apos;s Question")"> …
<a href="saveJob('He said "Go Away"')"> …
<a href='saveJob("He said \"Go Away\"")"> …
… and the following are invalid:
<a href="saveJob('Bob's Question')"> <!-- JS string ends early -->
<a href="saveJob("Bob's Question")"> <!-- HTML attribute ends early -->
<a href="saveJob('Bob&apos;s Question')"> <!-- JS string ends early -->
<a href="saveJob('He said "Go Away"')"> <!-- HTML attribute ends early -->
You cannot use your HTML attribute delimiter in your attribute value except as an HTML entity. You cannot use your JavaScript string delimiter in your JavaScript string unless you escape it, even if you use an HTML entity to describe it.
In general, you should not be putting JavaScript in your HTML (you should attach event handlers to your markup programmatically, from script), and you especially shouldn't be abusing an HTML anchor as a JavaScript trigger (either use an HTML anchor to a valid URL and let JavaScript hijack the link if enabled, or use a <button> or other element to invoke script-only side effects).
As you've noticed, such manual string escape tasks can be quite tricky; covering apostrophes won't even get you all the way: what if there's a newline in the string? That would break the script as well.
I would recommend converting your data to a JSON object, perhaps using JSON-taglib. This should take care of all required escaping for you.
The Phrogz solution
<a href="saveJob("Bob&apos;s Question")">
works fine if you have only apostrophes in your text.
If your text contains both apostrophes and quotes, you can use a hidden div (div with style='display:none;') for the text, pass the id of the div to saveJob instead of passing the text itself, and get the text inside saveJob by using
document.getElementById(myId).innerHTML

Categories