Smit Patel Smit Patel - 3 months ago 7
HTML Question

Forward Slashes ('/') not created in appending HTML - .append()

I'm trying to append the HTML section to my 'alert' box, Everything is working well except the URL in appended HTML. This is my HTML code to be appended using jQuery.

var html = "Please follow the template provided into sample file and try again.";
html += '<span onclick="window.location="\Static\SampleQuote.xlsx"> Click Here </span>To Download';
loadAlertPopupHTML("FAILED","Excel file parsing failed.",html);


I have tried with help of this answer, but I'm still not getting the exact syntax.

I tried each of these:

html += '<span onclick="window.location="\\Static\\SampleQuote.xlsx"> Click Here </span>';

html += '<span onclick="window.location=""/" \Static\SampleQuote.xlsx "/">
Click Here </span>';

html += '<span onclick="window.location="\Static\SampleQuote.xlsx">
Click Here </span>';


But output will be same without slash (
/
):

<span onclick="window.location=" staticsamplequote.xlsx"=""> Click Here </span>


You can also try here as an example: https://jsfiddle.net/smit_patel/exz6d1t3

Answer

The issue is due to the mis-matched quotes wrapping both the onclick attribute and the window.location assignment. You need to use escaped single quotes within the window.location assignment, and also escape the slashes. Try this:

var html = "Please follow the template provided into sample file and try again. <br /><br />";
html += '<strong><span onclick="window.location=\'\\Static\\SampleQuote.xlsx\'" class="fa fa-download" style="color:#0055a5; font-size:15px; cursor:pointer;" title="Click to Download Sample Template"> Click Here </span> to download excel template Employee Census Form.</strong>';
$("#test").append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

Better still, just use a standard <a /> element, as it has the same behaviour without the drawbacks of users who have disabled JS, and is more accessible.

var html = "Please follow the template provided into sample file and try again. <br /><br />";
html += '<strong><a href="\Static\SampleQuote.xlsx" class="fa fa-download" title="Click to Download Sample Template">Click Here</a> to download excel template Employee Census Form.</strong>';
$("#test").append(html);