Tknoobs
Tknoobs

Reputation: 169

How to deal with 3 times quotation marks in a onclick proberty of an element

I have a little problem: In my project I tried to make a like button and defined a button attached to a function via onclick proberty. But now it looks like this:

<div class="post-container">
    <button class="{% if post.liked %}color-blue{% else %}color-white{% endif %}" id="post_{{ post.id|stringformat:'s' }}" onclick="postLike('{{ post.id|stringformat:'s' }}')"> {{ number_of_likes }} Like{{ number_of_likes|pluralize }}</button>
</div>

Visual Studio Code red-marks this and I am not really sure how to handle these this, since I am getting an error on onclick in the Console when I press the button...

Upvotes: 2

Views: 131

Answers (2)

ARNON
ARNON

Reputation: 1217

To deal with 3 times quotation marks you need to switch between single and double quotes. Try doing this:

onclick='postLike("{{ post.id|stringformat:'s' }}")'

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370779

Inline handlers like you're currently using are universally considered to be terrible practice, and one of the reasons for that is because they have very ugly quote escaping problems when passing string parameters. (They also require global pollution and have a demented scope chain.)

Put the post ID into a data attribute instead, and attach listeners to each element in standalone JavaScript elsewhere. For example, if you're starting with

<button class="myButton" onclick="postLike('{{ post.id|stringformat:'s' }}')">

change to

<button class="myButton" data-post-id="{{ post.id|stringformat:'s' }}">

and retrieve the post ID from the button when clicked. After the HTML contains all the buttons, run the following JS:

for (const button of document.querySelectorAll('.myButton')) {
  button.addEventListener('click', (e) => {
    postLike(e.target.dataset.postId);
  });
}

You will have to tweak the selector string .myButton depending on the HTML markup around your buttons.

Another option, using event delegation on a container of all the buttons:

container.addEventListener('click', (e) => {
  if (e.target.dataset.postId) {
    postLike(e.target.dataset.postId);
  }
});

Upvotes: 1

Related Questions