0

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

4
  • If you must use onclick then add the quotes: onclick="AddItem('@Dish.DishName', '@Dish.Price')" - always check the rendered output as it should be clear that it's not putting proper strings into the onclick (and use correct " ' balance). Commented Jun 23, 2020 at 15:53
  • But then your function uses @Name - no need for that if you're passing it via javascript: function AddItem(Name,Price) { var txt = "<li>" + Name + " " + Price + "</li>" (or use string interpolation) Commented Jun 23, 2020 at 15:54
  • thanx freedomn-m. what do you mean by "if you must us onclick"? is it not a common thing to do, and if not what would be a better way? Commented Jun 23, 2020 at 17:44
  • onclick= is very outdated - there's various reasons such as the handler has to be global (can't be namespaced) and it's generally better to keep markup and application code separate. The better solution is described in Mohsen's answer. Commented Jun 23, 2020 at 20:50

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.