1

so I am trying to create a link within my page but for some reason it is getting disjointed the code is

data = data + "<li><a href='#' onclick='History.pushState({state:null},'article,"+rtndata[j].id+"','article'); return false;'>" + rtndata[j].title + "</a></li>";

rtndata[j].id is an id number and rtndata[j].title is a title both are being pulled from a db but when it renders in the browser it becomes

<a false;'="" return="" article,41','article');="" onclick="History.pushState({state:null}," href="#">Newsflash 5</a>

so what I to render is actually

<a href="#" onclick="History.pushState({state:null},'article,41','article'); return false;'>"Newsflash 5</a>;

Can anyone help me?

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Kern Elliott
  • 1,659
  • 5
  • 41
  • 65

1 Answers1

1

The value of the onclick attribute is enclosed within single quotes. Because of this, you have to either use " or &quot; (only for values) if you have to use quotes inside the attribute.

Because your JavaScript string is enclosed within double quotes ("), the double quotes have to be escaped before they can be used: "....onclick='...\"....'....";.

To fix your code, I have decided to use double quotes (escaped) instead of single quotes:

data = data + "<li><a href='#' onclick=\"History.pushState({state:null},'article,"+rtndata[j].id+"','article'); return false;\">" + rtndata[j].title + "</a></li>";

Detailled table:

JS string marker     Attribute marker       Valid attribute value markers
      "                \"                   '    &quot;
      "                '                    \"   &quot;
      '                "                    \'   &quot;
      '                \'                   "    &quot;
Rob W
  • 341,306
  • 83
  • 791
  • 678