2015-11-19 59 views
1

我有一个复选框(它使用Bootstrap Switch库作为开/关切换)以通过AJAX激活和停用用户。防止Javascript确认()在复选框状态更改

当用户取消选中此功能被激发箱:

$('.user-status-ckbx').on('switchChange.bootstrapSwitch'... 

的确认()则会弹出一个对话框,询问用户是否自己一定要DE /激活用户。如果用户单击“否”的按钮,使用送回其原始状态:

$("#" + e.currentTarget.id).bootstrapSwitch('toggleState'); 

我遇到的问题是,每个toggleState()运行时,switchChange.bootstrapSwitch也再次运行。这会产生一个无结束的confirm()消息,只有在用户确认消息时才会消失。

有没有一种有效的方法来防止switchChange.bootstrapSwitch方法运行基于真正的用户点击与编程生成的切换?

我已经尝试过:

e.originalEvent !== undefined 

e.which 

在其他类似的问题的建议,但没有这些工作,也没有他们甚至会出现在“e”的对象。 ..

<script> 
    $(".user-status-ckbx").bootstrapSwitch('size', 'mini'); 
    $(".user-status-ckbx").bootstrapSwitch('onText', 'I'); 
    $(".user-status-ckbx").bootstrapSwitch('offText', 'O'); 

    //ajax to activate/deactivate user 
    $('.user-status-ckbx').on('switchChange.bootstrapSwitch', function(e){ 

     var currentDiv = $("#" + e.currentTarget.id).bootstrapSwitch('state'); 
     if(currentDiv == false){ 
      var confirmed = confirm("Are you sure you wish to deactivate this user? They will no longer be able to access any forms."); 
      if(confirmed == true){ 
      changeActivationStatus($(this).val()); 
      } else { 
      $("#" + e.currentTarget.id).bootstrapSwitch('toggleState'); 
      } 
     } else { 
      var confirmed = confirm("Are you sure you wish to activate this user? Deactivated users which were previously active will have the same permissions prior to their de-activation unless changed manually."); 
      if(confirmed == true){ 
      changeActivationStatus($(this).val()); 
      } else { 
      $("#" + e.currentTarget.id).bootstrapSwitch('toggleState'); 
      } 
     } 
    }); 

    function changeActivationStatus(userId){ 
     $.post("{{ path('isactive') }}", {userId: userId}) 
      .done(function(data){ 
      console.log("Finished updating " + userId); 
      }) 
      .fail(function(){ 
      console.log("User could not be updated"); 
      }); 
    }; 
</script> 

回答

2

有一种方法来防止以编程方式切换时的事件。

你必须选项添加到引导开关:

var options = { 
     onSwitchChange: function (event, state) { 
      // Return false to prevent the toggle from switching. 
      return false; 
     } 
    }; 
$(".user-status-ckbx").bootstrapSwitch(options); 

当编程开关按钮,你就必须添加第二个参数:

$("#" + e.currentTarget.id).bootstrapSwitch('toggleState', true); 

的jsfiddle:https://jsfiddle.net/Ravvy/npz8j3pb/

+0

从Bootstrap Switch Doc:“方法toggleState可以接收可选的第二个参数skip,如果为true,则不执行switchChange事件,默认值为false。” 原来,您甚至不需要将onSwitchChange选项设置为false。这样做会产生相反的效果,即在用户点击“确认”时不切换状态。我会相应地编辑你的答案。谢谢 – Ravioli87