JQuery - 三态复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3101810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:52:48  来源:igfitidea点击:

JQuery - TriState CheckBox

jquery

提问by user336786

I'm trying to find a tri-state checkbox plugin. However, every plugin I find relies on a hierarchy (like a folder structure) of elements. I just have a single checkbox element that I want to make a three-way checkbox.

我正在尝试找到一个三态复选框插件。但是,我发现的每个插件都依赖于元素的层次结构(如文件夹结构)。我只有一个复选框元素,我想创建一个三向复选框。

Does anyone know of a jquery plugin that will do this? I'm really surprised I didn't find one that works on http://plugins.jquery.com/.

有谁知道可以做到这一点的jquery插件?我真的很惊讶我没有找到一个适用于http://plugins.jquery.com/ 的

Thank you for your input.

谢谢您的意见。

回答by Jeff

Some of these answers are a bit out of date since jQuery redid their plugin site.

其中一些答案有点过时了,因为 jQuery 重做了他们的插件站点。

"Tristate" (indeterminate) checkboxes are built right into JavaScript, and it's easy to set them into that state by simply setting a property on them. More info: http://css-tricks.com/indeterminate-checkboxes/

“三态”(不确定)复选框内置于 JavaScript 中,只需在其上设置属性即可轻松将它们设置为该状态。更多信息:http: //css-tricks.com/indeterminate-checkboxes/

$("#some-checkbox").prop("indeterminate", true);

$("#some-checkbox").prop("indeterminate", true);

There's a plugin available here on the new jQuery plugin site that provides that functionality: http://plugins.jquery.com/tristate-checkbox/

在提供该功能的新 jQuery 插件站点上有一个插件可用:http: //plugins.jquery.com/tristate-checkbox/

The three states are checked, unchecked, and indeterminate. It provided indeterminate state depending on whether all the child checkboxes are checked or not.

三种状态分别为选中、未选中和不确定。它根据是否选中所有子复选框提供不确定状态。

回答by Daniel Teixeira

回答by Niko

I came across the same issue - i needed it to show: enable/disable/ignore

我遇到了同样的问题 - 我需要它来显示:启用/禁用/忽略

Based on the icons available in jquery ui (http://jqueryui.com/themeroller/) I created following code (I know its not a plugin, but that wasnt necessary in my case):

基于 jquery ui ( http://jqueryui.com/themeroller/) 中可用的图标,我创建了以下代码(我知道它不是插件,但在我的情况下不需要):

The HTML I use is:

我使用的 HTML 是:

<input type="text" class="rotatestate" value="true"
 data-state-style="cursor:pointer"
 data-state-class="ui-icon"
 data-state-values='[{"value":"true","class":"ui-icon-check","title":"title for true"},{"value":"false","class":"ui-icon-radio-off","title":"title for off"},{"value":"null","class":"ui-icon-cancel","title":"title for third state"}]'/>

The control takes the json array in data-state-values for as many states as you want to rotate through:

该控件采用 data-state-values 中的 json 数组,用于您想要旋转的多个状态:

  • value: the value that will be entered in the input
  • class: css class(es) that the new span will have
  • title: an optional title that will be set in the created span
  • 值:将在输入中输入的值
  • 类:新跨度将具有的 css 类
  • 标题:将在创建的跨度中设置的可选标题

It basically creates a <span class="data-state-class + classOfState" title="titleOfState">element and on click updates it by cacling through the given value list.

它基本上创建了一个<span class="data-state-class + classOfState" title="titleOfState">元素,并在单击时通过遍历给定的值列表来更新它。

I coded it so it even allows change through other means (i.e. setting the value of the input directly) and updates the "control" when the $("input").change(); event is triggered.

我对它进行了编码,因此它甚至允许通过其他方式进行更改(即直接设置输入的值)并在 $("input").change(); 时更新“控件”;事件被触发。

The jquery code that handles it:

处理它的 jquery 代码:

/* rotatestate stontrol */
$("input.rotatestate", location).each(function(){
    var states = $(this).attr("data-state-values");
    var defaultClass = $(this).attr("data-state-class");
    // no need to continue if there are no states
    if(!states) {
        return;
    }

    try {
        states = JSON.parse(states);
    } catch (ex) {
        // do not need to continue if we cannot parse the states
        return;
    }

    var stateControl = $("<span></span>");
    if($(this).attr("data-state-style")) {
        stateControl.attr("style", $(this).attr("data-state-style"));
    }
    stateControl.data("states", states);
    stateControl.data("control", this);
    stateControl.data("activeState", null);
    $(this).data("control", stateControl);
    if(defaultClass) {
        stateControl.addClass(defaultClass);
    }

    // click on the control starts rotating
    stateControl.click(function(){
        var cState = $(this).data().activeState;
        var cStates = $(this).data().states;
        var control = $(this).data().control;
        var newState = null;

        if(cState != null) {
            // go to the 'next' state
            for(var i = 0; i < cStates.length; i++) {
                if(cStates[i].value === cState.value) {
                    // last element
                    if(i === cStates.length - 1) {
                        newState = cStates[0];
                    } else {
                        newState = cStates[i+1];
                    }
                    break;
                }
            }
        } else {
            // no state yet - just set the first
            newState = cStates[0];
        }

        $(control).attr("value", newState.value);
        // trigger change
        $(control).change();
    });

    // make sure to update state if the value is changed
    $(this).change(function(){
        var control = $($(this).data().control);
        var cState = control.data().activeState;
        var cStates = control.data().states;

        if(cState != null) {
            // remove "old state"
            control.removeClass(cState['class']);
        }

        // add new State
        var val = $(this).val();
        $.each(cStates, function(){
            if(this.value === val) {
                control.data().activeState = this;
                if(this.title) {
                    control.attr("title", this.title);
                }
                control.addClass(this['class']);
                return false;
            }
        });
    });

    // trigger initial state
    $(this).change();
    $(this).after(stateControl);
    $(this).hide();
});

The control is also part of my Form Controls Library on https://github.com/corinis/jsForm/wiki/Controls.

该控件也是我在https://github.com/corinis/jsForm/wiki/Controls上的表单控件库的一部分。

回答by Wolfgang Fahl

see my answer to Tri-state Check box in HTML?:

看到我对HTML 中三态复选框的回答了吗?

My proposal would be using

我的建议将使用

  • three appropriate unicode characters for the three states e.g. ❓,✅,❌
  • a plain text input field (size=1)
  • no border
  • read only
  • display no cursor
  • onclick handler to toggle thru the three states
  • 三种状态的三个合适的 unicode 字符,例如 ❓,✅,❌
  • 纯文本输入字段(大小=1)
  • 无边界
  • 只读
  • 不显示光标
  • onclick 处理程序在三个状态之间切换

See examples at:

参见示例:

HTML source:

HTML 源代码:

<input type='text' 
       style='border: none;' 
       onfocus='this.blur()' 
       readonly='true' 
       size='1' 
       value='&#x2753;' onclick='tristate_Marks(this)' />

or as in-line javascript:

或作为内嵌 javascript:

<input style="border: none;"
       id="tristate" 
       type="text"  
       readonly="true" 
       size="1" 
       value="&#x2753;"  
       onclick="switch(this.form.tristate.value.charAt(0)) { 
         case '&#x2753': this.form.tristate.value='&#x2705;'; break;  
         case '&#x2705': this.form.tristate.value='&#x274C;'; break; 
         case '&#x274C': this.form.tristate.value='&#x2753;'; break; 
       };" />

Javascript source code:

Javascript源代码:

<script type="text/javascript" charset="utf-8">
  /**
   *  loops thru the given 3 values for the given control
   */
  function tristate(control, value1, value2, value3) {
    switch (control.value.charAt(0)) {
      case value1:
        control.value = value2;
      break;
      case value2:
        control.value = value3;
      break;
      case value3:
        control.value = value1;
      break;
      default:
        // display the current value if it's unexpected
        alert(control.value);
    }
  }
  function tristate_Marks(control) {
    tristate(control,'\u2753', '\u2705', '\u274C');
  }
  function tristate_Circles(control) {
    tristate(control,'\u25EF', '\u25CE', '\u25C9');
  }
  function tristate_Ballot(control) {
    tristate(control,'\u2610', '\u2611', '\u2612');
  }
  function tristate_Check(control) {
    tristate(control,'\u25A1', '\u2754', '\u2714');
  }

</script>

回答by zevero

I run across this two-liner from https://css-tricks.com/indeterminate-checkboxes/

我从https://css-tricks.com/indeterminate-checkboxes/遇到了这个两行

$('#some_div').on('click','input[type=checkbox]', function(){
   if (this.readOnly) this.checked=this.readOnly=false;
   else if (!this.checked) this.readOnly=this.indeterminate=true;
});

I am usint this on https://github.com/zevero/jquery-checkbox-tablewhich will be available later this day.

我在https://github.com/zevero/jquery-checkbox-table上使用这个,这将在今天晚些时候提供。