concat ' in JS Code (Jquery)
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 ?
Answer
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 + '"' + ">"
....
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