I' using kind of two times validation to ensure the user really wants to delete the item.
<span class="addvalidationmsg" data-actionresult="DeleteInstallation">CLICK ME</span>
First when user click on item, I replace classes and change message, and no POST, just changes on DOM:
$(".addvalidationmsg").click(function () {
// remove validation message
$(this).removeClass("addvalidationmsg");
// add ajaxcall
$(this).addClass("ajaxcall");
// add text
$(this).text("are you sure? Click again");
return false;
});
Then, when I click the second time, thanks to the new class, it launchs this:
$(document).on("click", ".ajaxcall", function () {
alert("POST");
});
});
Problem is that I just want to launch POST only on the second click. If I return false on the first function, nothing happend after that and if I remove it, it launches the POST twice (once every click)
If I remove the return false; on the first function, then the second function is called when user press the item the first time (why again)?
How to make this work?
A little JSFIDDLE
Thanks in advance
The problem is that you are statically binding a click event to an element that you found using a class selector. It does not matter if the class is removed later as the handler is already bound to the element.
Change to a delegated event handler. This is then bound to an ancestor element instead:
$(document).on('click', ".addvalidationmsg", function () {
As the jQuery selector is only run at event time, not event registration time, it will no longer match when the class is removed and the event will not fire again.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/2xaa26yr/2/
Note: I had to put in a console.log as the repeated click was not "visible" :)
The second problem "was" the return false
stopping event propagation, but that goes away too with the above code.
If you never intend re-enabling the button, another option is to use one
instead. This will only fire the event once.... ever:
$(".addvalidationmsg").one('click', function () {