0

i am trying to use scripts to get data from my Webapi.

i have tried a few dozen or so different scripts, but nothing ever gets executed.

Script:

@section scripts
{
<script>
$(document).ready(function () {

    $('.cocktail').on('click', function () {
        $.getJSON(url + '/' + $(this).data('id'))
            .done(function (data) {
                $.each(data, function (key, item) {
                    $('<li>', { text: formatItem(item) })
                        .appendTo($('#ingredients'));
                })
            });
    });
});

function formatItem(item) {
    return item.name + item.Volume + item.Dosage;
}

}

HTML:

<div class="row">
<div class="col-md-6">
    <ul class="list-group">
        @foreach (CocktailBasic cocktail in Model)
        {
            <li>
                <b><a href="#" id="cocktail" data-id="@cocktail.Id" class="Cocktail">@cocktail.Name</a></b>
            </li>
        }
    </ul>
</div>

<div class="col-md-6">
    <h2>Ingredients</h2>
    <ul id="ingredients"></ul>
</div>

I am completly new to using scripts. everything other than the script works fine.

MindSwipe
  • 7,193
  • 24
  • 47

3 Answers3

1

There is no element with class cocktail, there is one with this ID and a Cocktail class.

You'll have to change your selector to $("#cocktail") or $(".Cocktail")

Titus
  • 22,031
  • 1
  • 23
  • 33
1

I see a couple of potential issues:

  • You are using the same ID "cocktail" multiple times - IDs need to be unique within the page

  • CSS classes are case sensitive - Your jquery selector is .cocktail but your css class is Cocktail.

mr.freeze
  • 13,731
  • 5
  • 36
  • 42
1

You have defined your class as class="Cocktail" and you have added click handler as $('.cocktail'). You should use, $('.Cocktail').

nilay
  • 365
  • 1
  • 10