Reputation: 4303
So, I'm having a bit of an issue. I have some links that when they are clicked run a function in jQuery, however, the first time I click the link nothing happens. If I click it again, the function runs twice, if I click it a third time, it runs three times off of that click.
Here is my jQuery code
function updateEntryStatus() {
var anime_id = <?php echo $anime_id; ?>;
var anime_list_entry_id = <?php echo $anime_list_entry_id; ?>;
jQuery('.wantedStatus').on('click', function(event)
{
var wantedStatus = jQuery(this).text();
jQuery.post("/wp-content/themes/sahifa/phanime_list/updateStatus_animelist.php", {firstParam : anime_id, secondParam : anime_list_entry_id, thirdParam : wantedStatus}, function(data) {
//this is your response data from serv
console.log(data);
jQuery('#anime_list_update').html(data);
});
return false;
});
}
and here are a couple of my links
<a href="javascript:void(0);" onclick="updateEntryStatus();" class="wantedStatus">Watching</a> |
<a href="javascript:void(0);" onclick="updateEntryStatus();" class="wantedStatus">Plan to watch</a> |
<a href="javascript:void(0);" onclick="updateEntryStatus();" class="wantedStatus">On hold</a> |
<a href="javascript:void(0);" onclick="updateEntryStatus();" class="wantedStatus">Dropped</a>
Example:
Click 1: Nothing happens
Click 2: function runs twice.
Click 3: function runs 3 times / in total runs 5 times.
Click 4: function runs 4 times / in total run 9 times and so on...
I am assuming is it's the way i've setup the click within my function.
Upvotes: 0
Views: 1558
Reputation: 2374
You don't setup the onclick
event until someone has clicked on the link. Each time they click on the link you setup another event handler.
Move the jQuery('.wantedStatus').on('click', function(event)
call outside of the updateEntryStatus()
function and ensure the .on()
function is called before someone clicks on the link.
Upvotes: 1
Reputation: 3665
Simply take this
jQuery('.wantedStatus').on('click', function(event)
{
var wantedStatus = jQuery(this).text();
jQuery.post("/wp-content/themes/sahifa/phanime_list/updateStatus_animelist.php", {firstParam : anime_id, secondParam : anime_list_entry_id, thirdParam : wantedStatus}, function(data) {
//this is your response data from serv
console.log(data);
jQuery('#anime_list_update').html(data);
});
return false;
});
}
part out of your updateEntryStatus() function.
Upvotes: 1