0

I have multiple list items in an unordered list. Each list item looks like this:

<li class="something" onclick="function(somePHPparameter)">somePHPparameter</li>

The function will populate a div that's currently empty via ajax, if that matters. I want it so that by default, when the page first finishes loading, clicking on the li will populate the div. If the same li is clicked again, then it will empty the div. If another li was clicked instead, just change the contents with a different "somePHPparameter". My current implementation is like this:

$('.continent').click(function(){
    if ($(this).hasClass('select')){
        $("#box").empty();
        $('.continent').removeClass('select');
    }
    else{
        $('.continent').removeClass('select');
        $(this).addClass('select');
    }
});

One, is there any faulty logic with my code? Anything extra? Two, the actual issue is that even though the class is removed, the onclick that populates the div still occurs. e.preventDefault() and e.stopPropagation() don't work. Any ideas?

2 Answers 2

1

event.preventDefault() and event.stopPropagation() will not help in this case because two different functions are already called when click is triggered. One function is called inline and the other is called using jQuery.

To avoid this, remove onclick attribute from <li> and call that function inside jquery click handler.

If it's PHP generated param, add it as a rel attribute to <li> and use in jquery handler like below:

<li class="something" rel="somePHPparameter">somePHPparameter</li>

--

$('.continent').click(function(){
if ($(this).hasClass('select')){
    $("#box").empty();
    $('.continent').removeClass('select');
}
else{
    $('.continent').removeClass('select');
    $(this).addClass('select');

    var PHPparam = $(this).attr('rel');

    functionCallUsing(PHPparam);
}

return false;
});

Just a rough idea.

Sign up to request clarification or add additional context in comments.

1 Comment

this worked wonderfully. Returning false wasn't necessary though.
0

You can simply do

$('.continent').click(function(){
    if ($(this).hasClass('select')){
        $("#box").empty();
        $('.continent').removeClass('select');
    }
    else{
        $('.continent').removeClass('select');
        $(this).addClass('select');
    }

    return false;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.