dimosbele
dimosbele

Reputation: 381

Javascript - Slashes are replaced by spaces

I am trying to create an li element in my html code via javascript. This li will have an onclick function. The problem is that trying to pass a file path as an argument in the loadDoc2() function, some problems occur. I am including the code.

    function myFunction(){ 
          var x = "NEW";
          var file = "'/static/BRANDS/PERLA/NEW COL/XML Files/NEW COL.xml'";
          lis = "<li><a onclick='loadXMLDoc2(" + file + ")'>" + x + "</a></li>";
          document.getElementById("demo").innerHTML = lis;
        }

This gives me <a onclick="loadXMLDoc2(" static brands perla new col xml files new col.xml')'>NEW</a>. The slashes are replaced by spaces and letters are low case. The result that I need is <a onclick="loadXMLDoc2('/static/BRANDS/PERLA/NEW COL/XML Files/NEW COL.xml')">NEW</a> I have tried many things such as .replace("\", "//") but it didn't work.

Upvotes: 1

Views: 497

Answers (3)

mousemke
mousemke

Reputation: 1

you appear to have conflicting quotes.

lis === "<li><a onclick='loadXMLDoc2('/static/BRANDS/PERLA/NEW-COL/XML-Files/NEW COL.xml')'>NEW</a></li>"

note that k='loadXMLDoc2('/ will open then close the quotes. fixed by changing single to double quotes:

var x = "NEW";
var file = "'/static/BRANDS/PERLA/NEW-COL/XML-Files/NEW COL.xml'";
lis = `<li><a onclick="loadXMLDoc2(${file})">${x}</a></li>`;
document.body.innerHTML = lis;

Upvotes: 0

Eladian
Eladian

Reputation: 958

<div id="container"></div>

<script>
 var container = document.getElementById('container');
 var li = document.createElement('li');
 li.innerText = "Im a list item";
 li.onclick = function(){
  console.log('I was clicked');
 }
 
 container.appendChild(li);
</script>

Upvotes: 0

Salketer
Salketer

Reputation: 15711

This happens because you start your onclick with ' and file has a ' at the start, so it closes the onclick attribute. So it looks like

<li><a onclick='loadXMLDoc2('/static/BRANDS/PERLA/NEW COL/XML Files/NEW COL.xml')'>NEW</a></li>

I suggest you use javascript to bind the event, it's gonna be way easier.

function myFunction(){ 
      var x = "NEW";
      var file = "/static/BRANDS/PERLA/NEW COL/XML Files/NEW COL.xml";
      var li = document.createElement('li');
      var a = document.createElement('a');
      a.innerHTML = x;
      a.onclick = function(){
          loadXMLDoc2(file);
      }
      li.appendChild(a);
      document.getElementById("demo").appendChild(li);
}

Upvotes: 3

Related Questions