-1

I have a piece of javascript that creates an HTML table, saving each row of the table into an array. I want one of the table cells on each row to be clickable.

The following code works fine and when cell3 is clicked, it displays a message box:

array.push("<tr><td>cell1</td><td>cell2</td><td onclick='alert(this);'>cell3</td></tr>")

My problem is that if I wanted the message box to say "hello", I can't get it to work because of the quotes, any ideas?

It's a quote within a quote within a quote and my brain is melting.

Thanks for any help in advance.

Lee
  • 13
  • 1
  • 2
    Did you try escaping the quotes? – pj013 Mar 31 '14 at 16:50
  • look at backslash sequences `test="\""` works for instance – mjb4 Mar 31 '14 at 16:50
  • Use the escape character `\\`, e.g. "alert(\"Hello\")" – kei Mar 31 '14 at 16:50
  • Fantastic! \"Hello\" worked perfectly. I had previously attempted to escape the quotes but unfortunately only tried \'Hello\' which did not work. Thanks for the help everyone, what a great resource this site is. – Lee Mar 31 '14 at 18:24

3 Answers3

1

try putting a backslash \ before the quotes around the word hello (for example).

you can programmatically do that if it works out for you when hardcoded... but let's see if it helps you first.

the following answer also suggests how to programmatically replace all quotes in your string with escaped quotes, so you don't have to hard code them:

How do I replace a double-quote with an escape-char double-quote in a string using javascript?

sample:

 str.replace(/"/g, '\\"');
Community
  • 1
  • 1
Don Kelley
  • 170
  • 6
  • note - others were suggesting the same thing in comments to your first post while I was writing my answer.... what I described is also escaping your quotes. – Don Kelley Mar 31 '14 at 16:51
0

You can escape the " char using the \ before, for sample:

array.push("<tr><td>cell1</td><td>cell2</td><td onclick=\"alert(this);\">cell3</td></tr>");
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
0

Does this work?

var alertMessage = "HELLO!";
array.push("<tr><td>cell1</td><td>cell2</td>
   <td onclick='alert(" + alertMessage  +");'>cell3</td></tr>")