2013-04-25 73 views
5

最近我一直在处理很多复选框。 我遇到了这个'问题'与.prevenDefault()点击事件,我试图找到一个解决方案。 在我的情况下,我希望能够决定是否可以根据其他字段选中/取消选中复选框。有时我甚至不得不在事件发生前打开一个对话框。 这听起来比它结果容易...Jquery复选框.prop点击防止默认行为

this jsFiddle你可以看到什么问题,以及我如何试图解决它(见下面的代码以及)。大多数答案暗示使用更改而不是点击。但比你不能使用.preventdefault()

$('div').off('change','.wtf').on('change', '.wtf', function(e) { 
    //e.preventDefault(); 
    //return false; 
    if($(this).prop('checked') == true) { 
     alert('I am true now, but I must stay false'); 
     $(this).prop('checked', false); 
    } 
    else { 
     alert('I am false now, but I must stay true'); 
     $(this).prop('checked', true); 
    } 
}); 

这是最好的解决方案吗?或者还有其他方法可以使复选框等待直到允许它改变它的状态吗?

作为例子:我想只有取消选中该复选框,如果用户通过点击“确定”按钮,在对话框的消息一致。

回答

8

复选框是一种特殊情况,其中change事件和click可以互相替换,因为change event也是通过单击复选框触发的。

也就是说clickchange之间唯一的一个很大的区别是.preventDefault()的可用性。如果使用除点击以外的其他方法更改复选框的值,则更改事件会更好。

在这种情况下,您可以选择您喜欢的任何一种。一个例子是:Fiddle here

$('input[type="checkbox"]').on('change', function() { 
    var ch = $(this), c; 
    if (ch.is(':checked')) { 
     ch.prop('checked', false); 
     c = confirm('Do you?'); 
     if (c) { 
      ch.prop('checked', true); 
     } 
    } else { 
     ch.prop('checked', true); 
     c = confirm('Are you sure?'); 
     if (c) { 
      ch.prop('checked', false); 
     } 
    } 
}); 
+0

感谢您的回答的功能。不过,如果您与其他表单元素处理进行比较,我仍然发现这些复选框有些不合逻辑... – Brainfeeder 2013-04-25 12:26:29

+0

确实如此,它们有点不同,因为它们具有值,但也处于开/关状态(已选中或未选中)。这使他们更棘手。 – Spokey 2013-04-25 12:31:14

+2

另请注意,点击和更改事件在Firefox和Chrome上触发的方式不同。 Firefox:首先点击,然后更改。 Chrome:先改变,然后点击。 – 2013-11-15 14:15:42

0

我已经实现Spokey解决方案基于一些修改,停止使用return如果confirm()回报true

$("input[name='status']").change(function(e){ 
     if ($(this).is(':checked')){ 
      msg = "{{__('The set status will be Active again! Are you sure?')}}" 
      a = confirm(msg); 
      if (a){ 
       return true; 
      } 
      $(this).prop('checked',false) 
     } 
     else{ 
      msg = "{{__('The set will be Inactive! Are you sure?')}}" 
      a = confirm(msg); 
      if (a){ 
       return true; 
      } 
      $(this).prop('checked',true); 
     } 
    })