I have a code in which I have three rows with three parameters $COKE, COKE, COKE. Every row has a sublist which opens when I click the parameters. It works fine when parameter doesnt have any special characters i.e.
For case when $COKE is parameter it doesn’t open sublist onclick. ($ dollar sign) For case when COKE is parameter it opens sublist onclick. For case when COKE. is parameter it doesn’t open sublist onclick. (. dot sign)
data[i].parameter="$COKE"
document.getElementById("results").innerHTML += "<tr id="+data[i].parameter+" onclick='showSublist(this.id)'>
data[i].paramater can have values as shown below $COKE, COKE.,COKE as an example. Image shown as reference, where only case 2 opens but case 1 and case 3 doesn’t open when I click them.
Advertisement
Answer
By not escaping special characters you are creating invalid HTML code, that’s why onclick doesn’t work.
Here is example how browser handles special characters:
function escape(a) {
return "&#" + a.charCodeAt(0) + ";";
}
function escapeText(text) {
return text.replace(/["'&<>]/g, escape);
}
function showSublist(id) {
alert(id);
}
var data = [{
parameter: "test"
},
{
parameter: "$test"
},
{
parameter: "<test"
},
{
parameter: "test>"
},
{
parameter: "<test>"
},
{
parameter: '"test'
},
{
parameter: 'test"'
},
{
parameter: '"test"'
},
{
parameter: "test."
},
{
parameter: '&test'
},
{
parameter: '&test;'
},
{
parameter: "test${test}"
},
];
for (let i = 0, tr = document.createElement("tr"); i < data.length; i++) {
tr = tr.cloneNode(false);
tr.innerHTML = '<td class="n">' + i + '</td>';
/* original, incorrect structure */
tr.innerHTML += "<td id=" + data[i].parameter + " onclick='showSublist(this.id)'>" + data[i].parameter + '</td>';
tr.innerHTML += '<td class="n">' + i + '</td>';
/* correct structure, no filter */
tr.innerHTML += '<td id="' + data[i].parameter + '" onclick="showSublist(this.id)">' + data[i].parameter + '</td>';
tr.innerHTML += '<td class="n">' + i + '</td>';
/* correct structure, filter */
tr.innerHTML += '<td id="' + escapeText(data[i].parameter) + '" onclick="showSublist(this.id)">' + escapeText(data[i].parameter) + '</td>';
tr.onmouseover = mouseOver;
document.getElementById("results").appendChild(tr);
};
var div = document.getElementById("html");
function mouseOver(e) {
html.textContent = e.target.className == "n" ? e.target.nextSibling.outerHTML : e.target.outerHTML;
}th {
text-align: start;
}
td:nth-child(even) {
border-right: 1em solid transparent;
}
td:hover {
background-color: rgba(0, 0, 0, 0.1);
cursor: pointer;
}
div {
background-color: white;
color: black;
position: fixed;
bottom: 0;
margin-top: 1em;
padding: 0.5em;
border: 1px solid black;
}
table {
margin-bottom: 3em;
}<table id="results">
<tr>
<th colspan="2">
Original, no quotes
</th>
<th colspan="2">
Unescaped
</th>
<th colspan="2">
Escaped
</th>
</tr>
</table>
<div id="html"></div>