Reputation: 10105
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?
Upvotes: 0
Views: 55
Reputation: 4603
Try this. (No guarantees since I can't test it). It demonstrates use of the .one()
version of .on()
that automatically unbinds once it's used
<script language="javascript">
$(document).ready(function() {
$('#btnSaveRole').on("click", function() {
$('#btnFinalSaveRole').one("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",
});
});
});
});
</script>
Upvotes: 1
Reputation: 207531
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");
});
});
Upvotes: 1