user348173
user348173

Reputation: 9288

selector don't work properly

I have 1 block:

<div class="going" filmid="2">
<a href="">I am going!</a>
<div>Going too: 20</div>
</div>

and 5 blocks:

<div class="going">
<a href="">I am going!</a>
<div>Going too: 20</div>
</div>

The difference in that one block have filmid attribute.
My js function:

function setUpUpdateGoingCount() {
            $("div.going a").click(function (e) {
                e.preventDefault();
                var filmId = $(this).parent("div").attr("filmid");
                $.post("/Cinema/UpdateGoingCount", { id: filmId }, function () {
                    alert("test");
                });
            });
        }

Click event work well with block without filmid atrribute.
Can you explain me why and how to do that first block works well?

Upvotes: 1

Views: 70

Answers (3)

I.G. Pascual
I.G. Pascual

Reputation: 5965

AJAX post is sent either way. The anchors (links) inside divs with filmid set, are sent with the param id set to the content of filmid. The divs not containing filmid are sent with the param empty.

UDATE If you mean by not working that the javascript doesn't show the alert message, that may be because you are getting an error on that call, and you'll need to specify an error function this way:

function setUpUpdateGoingCount() {
    $("div.going a").click(function(e) {
        e.preventDefault();
        var filmId = $(this).parent("div").attr("filmid");
        $.post("/Cinema/UpdateGoingCount", {
            id: filmId
        }, function() {
            alert("test");
        }).error(function() {
            alert("error");
        });
    });
}

This is a working example with your code http://jsfiddle.net/hpgsL/1/

Upvotes: 2

akuyume
akuyume

Reputation: 31

You'll need to add a second class to the blocks without the filmid to use in your selector as the .click is going to get binded to all div .going a whether they have a filmid attribute or not.

Upvotes: 0

Interrobang
Interrobang

Reputation: 17434

Because filmid is not an attribute that exists in HTML, you should instead use a data attribute:

<div class="going" data-filmid="2">

You can access this with:

var filmId = $(this).parent("div").data("filmid");

Upvotes: 4

Related Questions