0

How to use proper injection of product id in javascript.

  $(".vote_count").wrap("<a id='id' href='countvotes/{product_id}'</a>");

2 Answers 2

1

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.)

  1. String concatenation:

    $(".vote_count").wrap("<a id='id' href='countvotes/" + product_id + "'></a>");
    
  2. ES2015 (aka ES6) template strings:

    $(".vote_count").wrap(`<a id='id' href='countvotes/${product_id}'></a>`);
    
  3. 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 = {
    '&': '&amp;',
    '<': '&lt;',
    '"': '&quot;'
};
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.

Sign up to request clarification or add additional context in comments.

2 Comments

@DanielA.White: Done. And HTML handling, too. :-)
@T.J.Crowder Thank you very much!
1

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>`);

1 Comment

@Alexander Thanks for the help bro!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.