Reputation: 41
I'm trying to create a button that on click creates a list item and adds it to an existing list. the list item will contain data from my model(or rather my Db).
I'm trying to accomplish this with a jQuery function but having trouble with what parameters to send the function and how to use them.
This is the button:
<button onclick="AddItem(@Dish.DishName,@Dish.Price)">@Dish.DishName</button>
This is the jQuery function:
function AddItem(Name, Price) {
var txt1 = "<li > @Name @Price</li>"; // Create text with HTML
$(".list-group").append(txt1); // Append new elements
}
I'm pretty sure I'm not using @Razor
correctly, and would appreciate on any advice as to what to do to fix it And where I can find maybe some examples on js function that use razor cause I couldn't find much.
Thanks in advance
Upvotes: 0
Views: 342
Reputation: 11544
You can use data-*
attribute to store data and use that data by jquery:
<button data-name="@Dish.DishName" data-price="@Dish.Price" id="addButton">@Dish.DishName</button>
And in your js file:
$('#addButton').click(){
const name = $(this).attr("data-name");
const price = $(this).attr("data-price");
const item = `<li>${name} ${price}</li>`;
$(".list-group").append(item);
}
Upvotes: 1