Reputation: 2810
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?
Upvotes: 0
Views: 3172
Reputation: 819
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.
Upvotes: 1
Reputation: 9823
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;
});
Upvotes: 0