Home > Enterprise >  Pass pug variable inside function
Pass pug variable inside function

Time:01-22

I'm trying to pass a variable in my Pug code to an onSubmit event in a form element. Here's my code for that:

each post in posts    
   p() #{post.content}

   form(method='post' id="likeForm" target="invis" onSubmit="addLike(`${post._id}`)")

As you can see, in the addLike function, I'm trying to pass in the post._id variable. The variable is very much defined, and the function works, but I seem to be passing the variable into the function incorrectly. I also tried addLike(#{post._id}) but that doesn't work either. What am I doing wrong?

CodePudding user response:

It looks like you are trying to pass the post._id variable as a string argument to the addLike function using template literals (${post._id}) in a JavaScript event handler for the onSubmit attribute of the form. The correct way to pass the variable in this case is to remove the ` and ${} and just use post._id like this: onSubmit="addLike(post._id)" You also don't need to use #{post._id}

CodePudding user response:

It looks like you are trying to pass the post._id variable as an argument to the addLike function in the onSubmit attribute of the form element. However, the way you are passing the variable is not correct.

The issue is with the backticks () and the way you are trying to interpolate the variable. In JavaScript, you can use template literals (template strings) wrapped in backticks () to interpolate variables. To use template literals, you have to wrap your string with backticks() and to interpolate a variable you have to use ${variable}`.

You should change the function call to form(method='post' id="likeForm" target="invis" onSubmit="addLike(${post._id})")

Also, make sure that the addLike function is defined in your script.

Another way you can pass the variable is to use the data-* attribute, this is a way to store extra information on an HTML element. form(method='post' id="likeForm" target="invis" data-id=post._id) and then in your javascript

const form = document.querySelector('#likeForm');
form.addEventListener('submit', (event) => {
  event.preventDefault();
  const id = event.target.getAttribute('data-id');
  addLike(id);
});

It's worth noting that if you are using this method, you must use the event.target to get the element that triggers the event instead of this as the this keyword will refer to the submit function and not the form element.

I hope this helps, let me know if you have further questions.

  • Related