Helper Helper - 2 months ago 7
jQuery Question

Button gets clicked two times in background when clicking second time

I have following code in JQuery

<script language="javascript">
$(document).ready(function() {
$('#btnSaveRole').click(function(){
$('#btnFinalSaveRole').click(function() {
var $_Role = $('#txtRole').val();
var data = {
"Role" : $_Role
};
$.ajax({
url: 'http://localhost:1234/AdminSystem1/public/SaveRole',
method: "POST",
async: true,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function (msg) {
$("btnSaveRole").unbind('click');
$("btnFinalSaveRole").unbind('click');

},
error: function (jqXHR) {
$("btnSaveRole").unbind('click');
$("btnFinalSaveRole").unbind('click');
}
});
});
});
});

</script>


Issue is when I click on same button
btnSaveRole
again, it get clicked two times.

In order to fix that I used below code in success and fail callbacks

$("btnSaveRole").unbind('click');
$("btnFinalSaveRole").unbind('click');


Am I missing anything?

Answer

First click, you add an event to btnFinalSaveRole Second click, you add another event to btnFinalSaveRole

So of course when you click btnFinalSaveRole, you will have two clicks. Since you clicked btnSaveRole twice.

jQuery click() does not override events, it appends it to a list.

So appending an event inside another is normally a bad idea. Better idea is to bind outside. If you need to make sure X is clicked first, than make a boolean.

var clicked = false;
$("#btnSaveRole").on("click", function(){
    clicked = true;
});
$("#btnFinalSaveRole").on("click", function(){
    if(clicked) {
        alert("yahoo");
    }
});

other option would be to unbind the event, not the best, but can work.

$("#btnSaveRole").on("click", function(){
    $("#btnFinalSaveRole").off("click.val").on("click.val", function(){
        alert("hmmmm");
    });
});