How to use proper injection of product id in javascript.
$(".vote_count").wrap("<a id='id' href='countvotes/{product_id}'</a>");
If your question is: "I have a product_id variable and want to put it where I have {product_id} in this code," there are three answers: (The answers are essentially the same if you're talking about id instead, just make the appropriate changes.)
String concatenation:
$(".vote_count").wrap("<a id='id' href='countvotes/" + product_id + "'></a>");
ES2015 (aka ES6) template strings:
$(".vote_count").wrap(`<a id='id' href='countvotes/${product_id}'></a>`);
Any of several templating engines.
Usually, best to combine those with encodeURIComponent, because you're outputting a URI, and so if product_id has things in it (like /) that have special meaning in URIs, you need to escape them. So:
$(".vote_count").wrap("<a id='id' href='countvotes/" + encodeURIComponent(product_id) + "'></a>");
or
$(".vote_count").wrap(`<a id='id' href='countvotes/${encodeURIComponent(product_id)}'></a>`);
Taking that a bit further: Since you're outputting the content of an HTML attribute, you also have to ensure that what you're outputting is valid HTML text. There's no built-in for that, but it's a trivial function to write:
var escapes = {
'&': '&',
'<': '<',
'"': '"'
};
function escapeHTML(str) {
return str.replace(/[&<"]/g, function(ch) {
return escapes[ch];
};
}
(There's no need to escape >, but you can if you like.)
Using that, I always enclose my attributes in double quotes (since those are what I'm escaping).
So:
$(".vote_count").wrap('<a id="id" href="countvotes/' + escapeHTML(encodeURIComponent(product_id)) + '"></a>");
and
$(".vote_count").wrap(`<a id="id" href="countvotes/${escapeHTML(encodeURIComponent(product_id))}"></a>`);
Side note: You were missing the closing > on the <a tag. That's fixed in the above.
For ES5, like this
$(".vote_count").wrap('<a id="id" href="countvotes/' + encodeURIComponent(product_id) + '"></a>');
For ES6 you can use string templates
$(".vote_count").wrap(`<a id="id" href="countvotes/${encodeURIComponent(product_id)}"></a>`);