Floor
Floor

Reputation: 216

JQuery script is not working in ASP.NET MVC

I want a button to handle a certain JQuery function, but it is not doing anything.

The script inside my .cshtml file:

<script src="~/lib/jquery/dist/jquery.min.js">
    jQuery(function ($) {
        $('#swapHeart').on('click', function () {
            var $el = $(this),
                textNode = this.lastChild;
            $el.find('span').toggleClass('glyphicon-heart glyphicon-heart-empty');
            $el.toggleClass('swap');
        });
    });
</script>

and the button in my .cshtml file:

<button id="swapHeart" class="btn btn-default swap">
    <span class="glyphicon glyphicon-heart-empty"></span>
</button>

Why is this not working? Thanks in advance. EDIT: It does work in this codepen I created: https://codepen.io/floorvrmt/pen/qQPEKQ

Upvotes: 1

Views: 1590

Answers (1)

Anirudha Gupta
Anirudha Gupta

Reputation: 9289

Your code using the same script tag which is used to load the source of jQuery. Check the code below, in which I load the source and script

<script src="~/lib/jquery/dist/jquery.min.js">
</script>
<script>
    jQuery(function ($) {
        $('#swapHeart').on('click', function () {
            var $el = $(this),
                textNode = this.lastChild;
            $el.find('span').toggleClass('glyphicon-heart glyphicon-heart-empty');
            $el.toggleClass('swap');
        });
    });
</script>

Upvotes: 2

Related Questions