executable
executable

Reputation: 3600

Escape several single quote and double quote

I'm in trouble trying to escape several quotes.

Here is my code :

var somevalue = "test";
return $("<li onclick='document.getElementById(\"AddGenre\").value = " + '\'' + somevalue + '\'' ";'><div><img src='" + item.img + "'><span>" + somevalue + "</span></div></li>").appendTo(ul);

I got the following error :

Uncaught SyntaxError: missing ) after argument list

Upvotes: 1

Views: 81

Answers (2)

Cat
Cat

Reputation: 4246

I'm wasn't totally sure what value you wanted to assign to AddGenre when someone clicks a newly added list item -- but if I was right in thinking that value should be 'test', this code does exactly that in a whole different way.

I started by trying to avoid the need for the nested quotes, which the main function does by adding the elements to the DOM one at a time. A couple of helper functions make it look a little cleaner.

NOTE: Click "full-page" when running the snippet. (Otherwise, SO's console obscures a portion of the rendered DOM.)

var genresList = document.getElementById("genresList");
var AddGenre = document.getElementById("AddGenre");
appendLi("test");

console.log(genresList.outerHTML.split("><").join(">\n<"));

// Main function
function appendLi(someValue){

  // Defines elements
  const li = create("li"),
        div = create("div"),
        img = create("img"),
        span = create("span");

  // Modifies elements
  span.innerHTML = someValue;
  img.setAttribute("src","item.img");
  li.dataset.addGenre = `'${someValue}'`; // Stores value to use when li is clicked
  li.addEventListener("click", updateAddGenre); // Defines click listener
  
  // Appends elements to the DOM
  append(li, img);
  append(li, span);
  append(div, li);
  append(genresList, li);
}

// Handles clicks on added list items
function updateAddGenre(event){
  AddGenre.value = event.currentTarget.dataset.addGenre
}

// Sugar
function create(tagName){ return document.createElement(tagName); }
function append(parent, node){ parent.appendChild(node); }
<h5>AddGenres:</h5>
<input id="AddGenre" />

<h5>Genres List:</h5>
<ul id="genresList"></ul>

Upvotes: 1

junvar
junvar

Reputation: 11604

You're missing a +

"<li onclick='document.getElementById(\"AddGenre\").value = " + '\'' + somevalue + '\'' + ";'><div><img src='" + item.img + "'><span>" + somevalue + "</span></div></li>"
//                                                                                     ^^^

You should also look into template literals:

`<span>${myValue} and some quotes " ' "" ' '' no escapes needed</span`

Upvotes: 6

Related Questions