Question

Alright and my query is, How do I escape quotes in Javascript? I'm trying to alert the message with my code below. I know it won't work because it contains string in double quotes within the onClick function call and it gives the syntax error. How do I make it work? My condition is that I cannot use single quotes for parameter in my function call.

    <html>
    <head>
    <script type="text/javascript">
    function litString(vals)
    {
    alert(vals);
    }
    </script>
    </head>
    <body>

    <?php echo "Just for a Test<br/>"; ?>

    <a href="#" onClick="litString("test one")"><h2>JS String Literal</h2></a>
    </body>
    </html>

Update:

My actual intention is to make the below PHP+JS code combination work:

 echo '<li><a href="#" title="'.$res_bb['eng'].'" onClick=loadChap('.$res_bb['id'].','.$res_bb['chapters'].',"'.$res_bb['mal'].'")><font size="2">'.$res_bb['mal'].'</font></a></li>';
Was it helpful?

Solution

You escape quotes with backslash \.

<a href="#" onClick="litString(\"test one\")"><h2>JS String Literal</h2></a>

Or you can use single quotes:

<a href="#" onClick="litString('test one')"><h2>JS String Literal</h2></a>

Or you can use single quotes around the attribute, and double quotes inside:

<a href="#" onClick='litString("test one")'><h2>JS String Literal</h2></a>

If you're echoing the string, it gets a little trickier, because you also have to deal with PHP's quoting. Here I produce the second version above by escaping the single quotes.

echo '<li><a href="#" title="'.$res_bb['eng'].'" onClick="loadChap('.$res_bb['id'].','.$res_bb['chapters'].',\''.$res_bb['mal'].'\')"><font size="2">'.$res_bb['mal'].'</font></a></li>';

I just tested this with input:

$res_bb = array('eng'=> "Title", 'id'=> 10, 'chapters'=> 13, 'mal'=> "Foo bar");

The output was:

<li><a href="#" title="Title" onClick="loadChap(10,13,'Foo bar')"><font size="2">Foo bar</font></a></li>

OTHER TIPS

I suggest using addEventListener and data-* attributes for a cleaner approach:

<a href="#" id="someButton" data-litString="test one">...

<script>
  var link = document.getElementById('someButton');

  link.addEventListener('click', function () {
    var vals = this.getAttribute('data-litString');
    alert(vals);
  });
</script>

Use single quotes for the HTML attribute:

onClick='litString("test one")'

But that's not really a solution. You need to escape those double quotes somehow.

Maybe it's better to go this way...

<li><a href="#" title="<?php echo $res_bb['eng']; ?>" onClick=loadChap("<?php echo $res_bb['id']; ?>", "<?php echo $res_bb['chapters']; ?>"," <?php echo $res_bb['mal']; ?>")><font size="2"><?php echo $res_bb['mal']; ?></font></a></li>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top