-1

I am building an Object using vanilla JavaScript and one of the key pairs in the Object is an edit button that has a function being called onclick. I want to pass a parameter to this function when building the object but I cannot figure out the correct way to write the string.

You can see what I have tried in the code example below. I have not been able to get it to work properly.

new_projects.push({
      'Status': createStatusOrbs(project['Project Status'], 'Status'), 
      'Edit': "<i class='fa fa-pencil-square-o' aria-hidden='true' onclick='getEditForm("+project['Project']+")'></i>",
      'Project Name': project['Project'],          
      'Last Update': moment(project['Last Update']).format("MMM Do YYYY")


    });
NerdyDriod
  • 13
  • 2
  • 3
    Escape the quotes or use a template literal. Possible duplicate of [Escape quotes in JavaScript](https://stackoverflow.com/questions/2004168/escape-quotes-in-javascript) – Tyler Roper Aug 21 '19 at 16:57

1 Answers1

0

You can escape the quote using backslash \. For example, if you want a string "Hello" (including quotes), you can do this:

var str = "\"Hello\"";
console.log(str); // "Hello"

The same is the case with single quotes too.

In your case, you can escape it like this:

if (project['Project Status'] !== "Closed") {
    new_projects.push({ 
        'Status': createStatusOrbs(project['Project Status'], 'Status'),
        // Notice the escaped quote
        'Edit': "<i class='fa fa-pencil-square-o' aria-hidden='true' onclick='getEditForm(\'"+project['Project']+"\')'></i>", 
        'Project Name': project['Project'],
        'Last Update': moment(project['Last Update']).format("MMM Do YYYY") }); }

}

Or you can use template literals. For example, if you want to include a variable in a string, you can do this:

var x = 5;

// Notice that these are not single quotes. These are backticks
var y = `x = ${x}`;
console.log(y); // x = 5

In your case, you can use template literals as follows:

if (project['Project Status'] !== "Closed") {
    new_projects.push({ 
        'Status': createStatusOrbs(project['Project Status'], 'Status'),
        // Using template literal
        'Edit': `<i class='fa fa-pencil-square-o' aria-hidden='true' onclick="getEditForm('${project['Project']}')"></i>`, 
        'Project Name': project['Project'],
        'Last Update': moment(project['Last Update']).format("MMM Do YYYY") }); }

}

Learn more about template literals here

sanketd617
  • 809
  • 5
  • 16
  • Thank you for the information. The literals did not work for me but escaping out the variable did the trick! – NerdyDriod Aug 21 '19 at 19:28