【问题标题】:iCheck and manual setting of checkbox to checkediCheck 和手动设置复选框以选中
【发布时间】:2016-04-29 15:43:57
【问题描述】:

我正在使用iCheck framework,我有两个输入

<input name="group" id="id1" type="radio" checked>
<input name="group" id="id2" type="radio">
<input name="group" id="id3" type="radio">
<input name="group" id="id4" type="radio">

点击时我调用了一个 ajax 函数。如果某些事情失败了,我想将选中的属性设置回之前选择的输入。

var currentChecked = $("input[name='group']:radio:checked");

$("input[name='group']:radio").each(function() {
        $(this).on('ifChecked', function(){
               $.ajax({
                    url: "/ajax/something/"
                })
                .done(function (data) {
                    currentChecked = $(this);
                })
                .fail(function (data) {
                    $(this).removeAttr('checked');
                    currentChecked.prop('checked', true);
                });
 });
});

但这不会重置选中的复选框。我从 iCheck 框架中看不到什么?有什么解决办法吗?

【问题讨论】:

    标签: javascript jquery icheck


    【解决方案1】:

    实际上在iCheck 的情况下,您需要更新iCheck 以反映Jquery 上的更改。

    您可以使用iCheck('update')进行更新

    $(this).iCheck('update');
    

    使用 jquery 选中或取消选中单选按钮后。

    另一个解决方案只是 checkuncheck iCheck 使用他的预定义函数。

    <input name="group" id="id1" type="radio" checked>
    

    如果上面是您的单选按钮,您可以使用 jquery 部分中的代码,如下所示

    $('#id1').iCheck('uncheck'); //To uncheck the radio button
    $('#id1').iCheck('check'); //To check the radio button
    

    在这种情况下不需要使用iCheck('update')

    【讨论】:

      【解决方案2】:

      jQuery iCheck 的工作方式与您的预期有些不同。

      当您初始化复选框或单选按钮时,它会获取控件的状态/值并构建该状态的外观。就这些。然后它永远不会检查您的控件值或对其属性的任何更新。

      因此,在 Ajax 失败事件中取消选中复选框的唯一方法是使用插件公开的功能。

      您应该在 ajax 失败事件中使用以下命令将状态更改回以前的状态

      $(this).iCheck('toggle');
      

      或者您可以更改 html 属性并刷新控件,如下所示

      $(this).removeAttr('checked');
      currentChecked.prop('checked', true);
      $(this).iCheck('update'); — apply input changes, which were done outside the plugin
      

      【讨论】:

        【解决方案3】:

        以下解决方案在 iCheck v1.0.2 中对我有用。 您可以通过如下过滤单选按钮组来检查 iCheck 单选

        使用元素的“id”

        $('input:radio[name="group"]').filter('[id="id1"]').iCheck('check');
        

        使用“价值”

        $('input:radio[name="group"]').filter('[value="id1"]').iCheck('check');
        

        您可以根据您的要求/功能动态替换“id”或“value”。 您可以在 .iCheck('check') 中更改 'check' 或 'uncheck'。

        【讨论】:

          【解决方案4】:
          //this will update all iCheck fields inside the selected form
          $('#form_id :radio').iCheck('update');
          

          【讨论】:

          • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
          猜你喜欢
          • 1970-01-01
          • 2015-04-30
          • 1970-01-01
          • 2014-01-11
          • 1970-01-01
          • 2013-09-30
          • 2015-10-07
          • 1970-01-01
          • 2017-05-24
          相关资源
          最近更新 更多