【问题标题】:jQuery checkbox change and click eventjQuery复选框更改和单击事件
【发布时间】:2011-10-25 06:21:00
【问题描述】:

$(document).ready(function() {
  //set initial state.
  $('#textbox1').val($(this).is(':checked'));

  $('#checkbox1').change(function() {
    $('#textbox1').val($(this).is(':checked'));
  });

  $('#checkbox1').click(function() {
    if (!$(this).is(':checked')) {
      return confirm("Are you sure?");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox1"/><br />
<input type="text" id="textbox1"/>

这里.change() 使用复选框状态更新文本框值。我使用.click() 来确认取消选中的操作。如果用户选择取消,复选标记会恢复,但.change()会在确认之前触发。

这会使事情处于不一致的状态,并且在选中复选框时文本框会显示为 false。

如何处理取消并保持文本框值与检查状态一致?

【问题讨论】:

  • 它在 FF 和 chrome 中工作,并在 IE 8 中具有解释的行为。因此,请注意您需要在哪些浏览器中工作以及您在哪些浏览器中看到错误。跨度>
  • 这不是最好的,但我相信它对我有用:http://jsfiddle.net/Skooljester/2Xxcn/

标签: javascript jquery checkbox event-handling


【解决方案1】:

JSFiddle 中测试并满足您的要求。这种方法具有在单击与复选框关联的标签时触发的额外好处。

更新答案:

$(document).ready(function() {
    //set initial state.
    $('#textbox1').val(this.checked);

    $('#checkbox1').change(function() {
        if(this.checked) {
            var returnVal = confirm("Are you sure?");
            $(this).prop("checked", returnVal);
        }
        $('#textbox1').val(this.checked);        
    });
});

原答案:

$(document).ready(function() {
    //set initial state.
    $('#textbox1').val($(this).is(':checked'));

    $('#checkbox1').change(function() {
        if($(this).is(":checked")) {
            var returnVal = confirm("Are you sure?");
            $(this).attr("checked", returnVal);
        }
        $('#textbox1').val($(this).is(':checked'));        
    });
});

【讨论】:

  • 请注意,使用this.checked 比使用$(this).is(':checked') 快得多:jsperf.com/prop-vs-ischecked/5
  • @Dakota 当然,它要慢得多,但我们仍在谈论 600k 操作/秒。因此,每毫秒 600 次。我认为如果这开始在您的网页上引起性能问题,您可能需要重新评估您的 javascript ;) 不过,用代码理解性能指标是件好事。谢谢。
  • @MikeU:同意你关于过早优化的观点,但考虑到this.checked 编写 + 原生 javascript 的时间要短得多,一般来说它可能真的值得使用(除了 ~200 到 300快几倍)。
  • 我会推荐 .prop() 而不是 .attr() 因为后者在所有情况下都不起作用,我相信 jQuery 现在推荐 .prop()。
  • 我认为 [this] in $('#textbox1').val(this.checked);指文档。应该是 $('#textbox1').val($('#checkbox1').is(':checked'));
【解决方案2】:

Demo

使用mousedown

$('#checkbox1').mousedown(function() {
    if (!$(this).is(':checked')) {
        this.checked = confirm("Are you sure?");
        $(this).trigger("change");
    }
});

【讨论】:

  • 它在检查时显示警报,它总是阻止我检查事实。这是在 Chrome 上。
  • 与@pimvdm 相同。即使是检查动作也会弹出确认(它应该只弹出取消选中)并且选择 ok 不会导致选中该框。
  • 使用鼠标时有效,但使用键盘检查时无效。
  • @frinux 这很简单,因为这是一个与鼠标相关的问题。请不要因为答案与完全不同的问题的相关性而对答案投反对票。如果您在通过键盘检查复选框后触发指示器状态时遇到问题,请发布有关它的问题,而不是粗心地否决答案。
  • 投反对票,因为 mousedown 不是用户与复选框交互的唯一方式。
【解决方案3】:

如果您使用&lt;label for="cbId"&gt;cb name&lt;/label&gt;,大多数答案(大概)都不会抓住它。这意味着当您单击标签时,它将选中该框,而不是直接单击该复选框。 (不完全是问题,但各种搜索结果往往会出现在这里)

<div id="OuterDivOrBody">
    <input type="checkbox" id="checkbox1" />
    <label for="checkbox1">Checkbox label</label>
    <br />
    <br />
    The confirm result:
    <input type="text" id="textbox1" />
</div>

在这种情况下你可以使用:

Earlier versions of jQuery:

$('#OuterDivOrBody').delegate('#checkbox1', 'change', function () {
    // From the other examples
    if (!this.checked) {
        var sure = confirm("Are you sure?");
        this.checked = !sure;
        $('#textbox1').val(sure.toString());
    }
});

JSFiddle example with jQuery 1.6.4

jQuery 1.7+

$('#checkbox1').on('change', function() { 
    // From the other examples
    if (!this.checked) {
        var sure = confirm("Are you sure?");
        this.checked = !sure;
        $('#textbox1').val(sure.toString());
    }
});

JSFiddle example with the latest jQuery 2.x

  • 添加了 jsfiddle 示例和带有可点击复选框标签的 html

【讨论】:

  • 这是#OuterDivOrBody 不是.OuterDivOrBody :)
  • 我知道这是 SUPER OLD 但我发现它正在寻找其他东西并想让您知道在第二个示例中(我没有检查第一个小提琴)如果该人单击取消,您仍在取消选中并显示为假,如果他们取消,则应将其保留为选中并说真。以防万一你想修复它。
【解决方案4】:

好吧..只是为了避免头痛(这里已经过了午夜),我可以想出:

$('#checkbox1').click(function() {
  if (!$(this).is(':checked')) {
    var ans = confirm("Are you sure?");
     $('#textbox1').val(ans);
  }
});

希望对你有帮助

【讨论】:

    【解决方案5】:

    迟到的答案,但您也可以使用on("change")

    $('#check').on('change', function() {
         var checked = this.checked
        $('span').html(checked.toString())
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" id="check"> <span>Check me!</span>

    【讨论】:

    • 谢谢,上面的答案很详细,你的很简单,够用了。谢谢
    【解决方案6】:

    对我来说这很好用:

    $('#checkboxID').click(function () {
        if ($(this).attr('checked')) {
            alert('is checked');
        } else {
            alert('is not checked');
        }
    })
    

    【讨论】:

    • 通过网络搜索发现了这个。你应该使用 'prop' 而不是 'attr' >> api.jquery.com/prop
    【解决方案7】:

    你来了

    HTML

    <input id="ProductId_a183060c-1030-4037-ae57-0015be92da0e" type="checkbox" value="true">
    

    JavaScript

    <script>
        $(document).ready(function () {
    
          $('input[id^="ProductId_"]').click(function () {
    
            if ($(this).prop('checked')) {
               // do what you need here     
               alert("Checked");
            }
            else {
               // do what you need here         
               alert("Unchecked");
            }
          });
    
      });
    </script>
    

    【讨论】:

      【解决方案8】:

      去掉 change 事件,改为在 click 事件中更改文本框的值。与其返回确认结果,不如在 var 中捕获它。如果为真,则更改该值。然后返回 var。

      【讨论】:

        【解决方案9】:

        复选框单击并检查同一事件循环中的值是问题。

        试试这个:

        $('#checkbox1').click(function() {
            var self = this;
            setTimeout(function() {
        
                if (!self.checked) {
                    var ans = confirm("Are you sure?");
                    self.checked = ans;
                    $('#textbox1').val(ans.toString());
                }
            }, 0);
        });
        

        演示:http://jsfiddle.net/mrchief/JsUWv/6/

        【讨论】:

          【解决方案10】:

          如果您使用的是 iCheck Jquery,请使用以下代码

           $("#CheckBoxId").on('ifChanged', function () {
                          alert($(this).val());
                      });
          

          【讨论】:

            【解决方案11】:

            试试这个

            $('#checkbox1').click(function() {
                    if (!this.checked) {
                        var sure = confirm("Are you sure?");
                        this.checked = sure;
                        $('#textbox1').val(sure.toString());
                    }
                });
            

            【讨论】:

              【解决方案12】:
              $(document).ready(function() {
                  //set initial state.
                  $('#textbox1').val($(this).is(':checked'));
              
                  $('#checkbox1').change(function() {
                      $('#textbox1').val($(this).is(':checked'));
                  });
              
                  $('#checkbox1').click(function() {
                      if (!$(this).is(':checked')) {
                          if(!confirm("Are you sure?"))
                          {
                              $("#checkbox1").prop("checked", true);
                              $('#textbox1').val($(this).is(':checked'));
                          }
                      }
                  });
              });
              

              【讨论】:

                【解决方案13】:
                // this works on all browsers.
                
                $(document).ready(function() {
                    //set initial state.
                    $('#textbox1').val($(this).is(':checked'));
                
                    $('#checkbox1').change(function(e) {
                        this.checked =  $(this).is(":checked") && !!confirm("Are you sure?");
                        $('#textbox1').val(this.checked);
                        return true;
                    });
                });
                

                【讨论】:

                  【解决方案14】:

                  只需使用点击事件 我的复选框 id 是 CheckAll

                       $('#CheckAll').click(function () {
                  
                          if ($('#CheckAll').is(':checked') == true) {
                  
                               alert(";)");
                        }
                      });
                  

                  【讨论】:

                    【解决方案15】:
                    $('#checkbox1').click(function() {
                        if($(this).is(":checked")) {
                            var returnVal = confirm("Are you sure?");
                            $(this).attr("checked", returnVal);
                        }
                        $('#textbox1').val($(this).is(':checked')); 
                    });
                    
                    
                    <div id="check">
                        <input type="checkbox" id="checkbox1" />
                        <input type="text" id="textbox1" />
                    </div>
                    

                    【讨论】:

                      【解决方案16】:

                      我不知道为什么每个人都把事情搞得这么复杂。 这就是我所做的一切。

                      if(!$(this).is(":checked")){ console.log("on"); }
                      

                      【讨论】:

                        【解决方案17】:

                        通过名称获取电台值

                         $('input').on('className', function(event){
                                console.log($(this).attr('name'));
                                if($(this).attr('name') == "worker")
                                    {
                                        resetAll();                 
                                    }
                            });
                        

                        【讨论】:

                          【解决方案18】:

                          试试

                          checkbox1.onclick= e => {
                            if(!checkbox1.checked) checkbox1.checked = !confirm("Are you sure?");
                            textbox1.value = checkbox1.checked;
                          }
                          <input type="checkbox" id="checkbox1" /><br />
                          <input type="text" id="textbox1" value='false'/>

                          【讨论】:

                            【解决方案19】:

                            试试这个:

                                let checkbox = document.getElementById('checkboxId');
                                if (checkbox.checked != true)
                                {
                                    alert("select checkbox");
                                }
                            

                            【讨论】:

                              【解决方案20】:
                               $("#person_IsCurrentAddressSame").change(function ()
                                  {
                                      debugger
                                      if ($("#person_IsCurrentAddressSame").checked) {
                                          debugger
                              
                                      }
                                      else {
                              
                                      }
                              
                                  })
                              

                              【讨论】:

                              • 仅代码的答案被认为是低质量的:请务必说明您的代码的作用以及它如何解决问题。如果您可以在帖子中添加更多信息,它将帮助提问者和未来的读者。另请参阅解释完全基于代码的答案:meta.stackexchange.com/questions/114762/…
                              猜你喜欢
                              • 2012-06-27
                              • 1970-01-01
                              • 1970-01-01
                              • 2013-08-10
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 2018-05-01
                              • 2012-01-15
                              相关资源
                              最近更新 更多