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 ?
Answer
$('.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 \
.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM