I have a table called Gerechten with the columns: id, gerecht, beschrijving, categorie, prijs, url and sterren. In this table i have a lot of rows, so i used a jinja loop in the html script to loop through every row and display them, every div is its own meal, so i have a purchase button at the bottom of every div. I was wondering how i could get the id of the meal that was purchased and use it in a javascript script. so that i can add it to the cart.
this is my table in flask:
class Gerechten(db.Model):
__bind_key__ = 'gerechten'
__tablename__ = 'gerechten'
id = db.Column(db.Integer, primary_key=True)
gerecht = db.Column(db.String(80), index=True, unique=True)
beschrijving = db.Column(db.String(80), index=True)
categorie = db.Column(db.String(80), index=True)
prijs = db.Column(db.Integer, index=True)
sterren = db.Column(db.Integer, index=True)
url = db.Column(db.String(120), index=True)
db.create_all()
This is my jinja script:
{% for gerecht in gerechten %}
<div class="Gerechtdiv">
<img src={{gerecht.url}} class="gerechtimg">
<h3 class="GerechtTitel">{{gerecht.gerecht}}</h3>
<p class ="GerechtBeschrijving">{{gerecht.beschrijving}}</p>
<div class ="BottomGerechtDiv">
<p style="font-size: 17px;"><b>€{{gerecht.prijs}}</b></p>
<p>{{gerecht.sterren}}★</p>
</div>
<button class="button" onclick=""><span>Voeg toe aan winkelwagen</span></button>
</div>
{% endfor %}```
I havent tried anything yet, cause i just cant figure it out
2
Answers
To achieve this, you can modify your HTML and JavaScript to capture the id of the meal when the "Voeg toe aan winkelwagen" button is clicked. Here’s how you can do it:
Pass the id of the meal as a parameter to a JavaScript function when the button is clicked.
Define a JavaScript function that receives the id parameter and performs the necessary actions, such as adding the meal to the cart.
Here’s the modified code:
In this code:
We’re passing the id of the meal as a parameter to the addToCart JavaScript function when the button is clicked.
You can replace the console.log statement inside the addToCart function with any actions you want to perform when a meal is added to the cart, such as making an AJAX request to the server to add the meal to the cart.
Remember to include the necessary libraries (e.g., jQuery) if you’re making AJAX requests.
I encountered a similar error when trying to implement like functionality in my social media app
The best way to go about this is to add a data-id attribute and pass in the id to the function using the jinja templating:
and then in your script:
Make sure just to change the function name the event parameter is required.