Search code examples
javascriptjquerystring-concatenationstring-interpolation

jQuery String concatenation '+' error


I have a jQuery statement

 $('.searchDisplay').append('<i class="ion-email" onclick="copyEmail('+data[i].email+')"></i>' );

Here if I click this icon then this function copyEmail() is called which takes a string as an argument and adds it to the clipboard.

But when I click on the icon I get an error in my console

Uncaught SyntaxError: Invalid or unexpected token

then I tried doing it this way

$('.searchDisplay').append('<i class="ion-email" onclick="copyEmail("'+data[i].email+'")"></i>' );

I got this error

Uncaught SyntaxError: Unexpected token }

The problem is that I'm not able to pass a string in function.

Can someone slove this for me ?


Solution

  •  $('.searchDisplay').append('<i class="ion-email" onclick="copyEmail(\''+data[i].email+'\')"></i>' );
    

    Problem in your code was...

    When you call a function with string as an argument you do someFunction('somestring');, in your code you are missing the '' wrapping the string.

    So you need to wrap data[i].email with ' .. '. I have wrapped the data[i].email with '' but as there was already one pair so I had to escape it with \.