concat ' in JS Code (Jquery)

- 1 answer

Ad

Hi together I've got a problem with the ' and " in my js code.

   $(".searchResultsMember table").append("<tr>" +
              "<td>" +
              "<a href='#' title='Statistik' data-container='body' 
data-toggle='tooltip' data-placement='bottom' onclick='open_statistic('/memberships/statistik/', '"+ 
data.results[i].firstname +" "+ 
data.results[i].lastname +"','"+ data.results[i].id +
"');return false; '><img src='/images/iconpack/table.png' alt='Statistic'/></a> "+
     [....]

The Problem is in the onclick part .. can someone help me with this ?

Ad

Answer

Ad

In JavaScript, you can mix and match ' and " as long as you use them in pairs, eg:

var x = "a";
var y = 'b';

You can also combine these on the same line, eg:

var z = "a" + 'b';

so you pick the one you need depending on the content (unless you have some nefarious coding standards written by someone that doesn't understand this (which I've seen..))

to concat a single quote, surround in doubles and the other way, eg:

var x = "'" + '"';   x == '"

this also applies to attributes:

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="#" title='double quote (")'>
<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="#" title="single quote (')">

so you can fix your code by changing the quotes:

$(".searchResultsMember table").append(
          "<tr>"
          + "<td>"
          + "<a href='#' title='Statistik'" 
          + " data-container='body' data-toggle='tooltip' data-placement='bottom'"
          + ' onclick="open_statistic('  
          + "'/memberships/statistik/', '"
          + data.results[i].firstname 
          + " " 
          + data.results[i].lastname 
          + "','" 
          + data.results[i].id 
          + "');return false; "
          + '">'
          + "<img src='/images/iconpack/table.png' alt='Statistic'/></a> "+
[....]

But, having done this for you above - it's really confusing! (and therefore prone to errors)

So break it up into steps with variables, and break out just the double quotes, eg:

var onclick = "open_statistic('/memberships/statistik/', '" + ... + "');return false;";

$(".searchResultsMember table").append(
          "<tr>"
          + "<td>"
          + "<a href='#' title='Statistik'" 
          + " data-container='body' data-toggle='tooltip' data-placement='bottom'"
          + " onclick=" + '"' + onclick + '"' + ">" 
          ....
Ad
source: stackoverflow.com
Ad