Eddie D.
Eddie D.

Reputation: 145

disable a link after it's selected

when i click on link it gets a class named selected after it gets this class it needs to be disabled until it loses the class "selected" but it can't affect other li without class or with class "none"

    function abrePlanta(idPlanta, desc, image){
    h = screen.height;

    if ($('li').hasClass("selected")) {
        return false;
    }

    $('#image_preview').html('<img src="../interface_test/images/loading.gif" />');
    $('ul li.selected').removeClass('selected').addClass('none');
    $(this).closest('li').addClass('selected').removeAttr("disabled");

    if(h >= 960){
       size = 100;
    } else if(h < 960){
        size = 90;
    }

   $.get('2.php', { id_planta: idPlanta, size: size }, function(img){
        $('#image_preview').html(img);
   });
   $('#description').html(desc);
   $("#imagezoom").attr("src", "../../images/plantas/sso/" + image);
   return false;
}

<li><a href='javascript:void(0);' onclick="return abrePlanta.call(this, 2, "text", "image.jpg")"></a></li>

and it doesn't work event.preventDefault

i'm using onclick with a function

Upvotes: 0

Views: 139

Answers (3)

Rooster
Rooster

Reputation: 10077

hard to tell without seeing more of your code, but at a glance

Change:

if($(this).hasclass('selected')){

to

if($(this).hasClass('selected')){

capital C in hasClass

Also, based on your edit, right now you're checking all li elements in the document for the selected class with:

if ($('li').hasClass("selected")) {
    return false;
}

You should just be checking the li thats wrapping the a thats clicked if I understand what you're asking. So do something like this instead(this assumes that idPlanta is a js reference to the link that is clicked which is what it looks like you're trying, but can't be certain because your code didn't compile in a js fiddle when I tried to build it),

if ($(idPLanta).parent().hasClass("selected")) {
    return false;
}

Upvotes: 3

Richard
Richard

Reputation: 6354

Here is a JSFiddle that may help you figure some things out...


Your problem is where you declare the function:

<a href="#" onclick="myfunction()">test2</a>

This will call the function (which returns true/false), but it doesn't do anything with it. To cancel the event bubbling, you need to return the results of the function:

<a href="#" onclick="return myfunction()">test2</a>

This will return the "false" from the function, which will cancel the natural click event.

Upvotes: 1

thedevlpr
thedevlpr

Reputation: 1101

if($(this).hasClass('selected')){
    $(this).attr("disabled","disabled");
    return false;
} 
else {
    return true;
}

$('ul li.selected').removeClass('selected').addClass('none');
$(this).closest('li').addClass('selected').removeAttr("disabled");

<li><a href="#" onclick="function()">test</a></li>
<li><a href="#" onclick="function()">test2</a></li>

Upvotes: 0

Related Questions