PreventDefault not working on second click
jquery, preventdefault
Solution
My guess is that `run_ajax` is replacing the links with new ones. `.click` only binds to the elements that matched the selector at that time. The newly added links won't have a click event bound to them.
You need to make the events "live". Bind them using `.on` like so:
jQuery(document).on('click', '.selectview', function (ev) {
ev.preventDefault();
// code...
});
This will "delegate" the event. It will run for all `.selectview` links no matter when they are added to the DOM.
Problem
I have the following html code: ``` <div> <span>Products per page:</span> <a class="selectview" href="/womens-clothing/shorts?page=1&view=20">20</a> <a class="selectview" href="/womens-clothing/shorts?page=1&view=200">200</a> <div> ``` and the jQuery is as follows: ``` jQuery('.selectview').click(function (ev) { ev.preventDefault(); var alink = jQuery(this).attr('href'); var view = getLinkVars(alink)["view"]; var page = jQuery("#currentpageno").val(); alert(alink); alert(view); alert(page); run_ajax(view,page); }); ``` The code runs fine the first time if I click on any of the links; I see the alerts and the ajax code runs fine, but when I click on it the second time, the whole page is refreshed and no alerts are shown. Then if I click on it again it works, then when I click on it again it works, and so on. What could I be doing wrong?