esafwan esafwan - 5 months ago 8
jQuery Question

If conditions false then prevent default

I have a link. When some one clicks on that I want to check some conditions before letting it work. If it's

false
the default action should be prevented.

$(".pager-next a.active").click(function(event) {
if (!a == 1) {
event.preventDefault();
}
});


The link should only work if
a
is equal to
1
. Is the above code correct.
a
is set to
1
if a particular condition is met. The link should only work if the condition is met.

Answer

Assuming by 'should only work if a is equal to 1' you mean the text of the a element is equal to 1, try this:

$(".pager-next a.active").click(function(event) {
    if ($(this).text() != "1") {
        event.preventDefault();
    }           
});

You can amend text() to use whichever attribute of the element is available to you in jQuery.

UPDATE

my a is a var which hold the value 0 until a condition is met.

In which case, the problem was simply that your equality operator was incorrect:

$(".pager-next a.active").click(function(event) {
    if (a != 1) {
        event.preventDefault();
    }            
});
Comments