从代码中更改Switchery复选框状态

39
我如何以编程方式从选中状态到未选中状态(反之亦然)更改jQuery Switchery复选框的状态?我尝试在复选框元素上使用global_switch_sound.prop('checked', true),但它不起作用。
HTML:
<input id="sound-active-input" type="checkbox"  />

JavaScript:

 global_switch_sound = new Switchery(document.querySelector('#sound-active-input'));

1
你有代码给我们吗? - Rickert
22个回答

47

试试这个:

$('.switchery').click();

它应该触发一个点击并切换。 或者是这个:

$('.switchery').trigger('click');

这将改变呈现的复选框的状态,但是当我运行函数global_switch_sound.markedAsSwitched()时,它始终返回"true",无论复选框的状态如何。 - Liron Harel
好的,这个应该没问题,因为我已经对元素运行了“isChecked()”函数,并且它显示了正确的状态。你知道是否有原生函数可以更改状态,而不是使用这种解决方法吗? - Liron Harel
我从未使用过这个插件,但在插件页面上找不到任何内容。 - Rickert
点击触发器出现问题了,我认为这可能是由于插件将ID复制到开关的新span元素中导致的..正在检查中.. - Liron Harel
你确定它是在开关元素上触发的吗? - Rickert
显示剩余4条评论

32

如果有人和我一样,想要一个超越 ".click()" 操作 DOM 的解决方案。下面的函数接受 Switchery 对象和一个布尔值来指示开关是否应该被选中或取消选中(分别为 true / false):

function setSwitchery(switchElement, checkedBool) {
    if((checkedBool && !switchElement.isChecked()) || (!checkedBool && switchElement.isChecked())) {
        switchElement.setPosition(true);
        switchElement.handleOnchange(true);
    }
}

使用示例:

var mySwitch = new Switchery($('#mySwitchCheck')[0], {
            size:"small",
            color: '#0D74E9'
        });
//Checks the switch
setSwitchery(mySwitch, true);
//Unchecks the switch
setSwitchery(mySwitch, false);

希望这能帮助到其他人


我使用了Aamir的解决方案和该条件一起(在页面加载时使用分配的Switchery对象数组)。这样我就避免了重新创建new Switchery对象。 - CPHPython
它比被接受的答案更好,因为它也适用于禁用的开关。 - Călin Darie
“if”条件可以更改为:if(checkedBool !== switchElement.isChecked()) { ... } - Orca

15

试试这个:

function changeSwitchery(element, checked) {
  if ( ( element.is(':checked') && checked == false ) || ( !element.is(':checked') && checked == true ) ) {
    element.parent().find('.switchery').trigger('click');
  }
}

使用示例:

var element = $('#sound-active-input');
changeSwitchery(element, false);

我认为这是最简单和最灵活的答案。你可以通过使用 element.click() 来使它变得更简单。谢谢! - Arian Acosta
这太棒了 ;) - Hamed B

8
你可以简化这个过程:
// Uncheck: first set checked property to 'true', then uncheck to force UI update
$(".switchery").prop('checked', false).trigger("click");

// Check
$(".switchery").prop('checked', true).trigger("click");

7

在初始化时,首先必须将所有的开关存储在一个数组中

var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function(html) {
    switchery[html.getAttribute('id')] = new Switchery(html);
});

并创建一个本地函数来切换开关,就像这样:
toggleSwitchery(id)
{
    var s = switchery[id];
    s.setPosition(true);
    s.handleOnchange(true);
}

这对我很有帮助。如果您遇到任何UI问题,即开关移动了一些额外的像素,请打开switchery.js并在Switchery.prototype.setPosition函数中将jack.offsetWidth替换为30。

谢谢...我已经搜索了两天了。 - Kashif Hanif

4
function toggleSwitch(switch_elem, on) {
    if (on){ // turn it on
        if ($(switch_elem)[0].checked){ // it already is so do 
            // nothing
        }else{
            $(switch_elem).trigger('click').attr("checked", "checked"); // it was off, turn it on
        }
    }else{ // turn it off
        if ($(switch_elem)[0].checked){ // it's already on so 
            $(switch_elem).trigger('click').removeAttr("checked"); // turn it off
        }else{ // otherwise 
            // nothing, already off
        }
    }
}

使用调用

toggleSwitch("#switch_element", true);
toggleSwitch("#switch_element", false);

该代码需要进行错误检查等工作,但运行良好,需要使用jQuery,并在我使用的预构建主题(Altair Admin)中测试了Switchery 0.8.1。


4

当您需要勾选/取消所有Switchery复选框时,使用JQuery的解决方案如下:

$( '.js-switches' ).each( function() {
// for checking
    if ( !this.checked ) $( this ).trigger( 'click' );
// for unchecking
    if ( this.checked ) $( this ).trigger( 'click' );
} );

希望这能有所帮助。

2

试试这个:

function changeSwitch(switch_id,active) {
    var check = document.querySelector(switch_id);
    //console.log("check",switch_id,check.checked,"to",active);
    if ( !check.checked && active ){
        var c = $(check).next('span').attr("class").replace("switchery ","");
        var l = {"switchery-large":"26px","switchery-small":"13px","switchery-default":"20px"}; 
        $(check).prop("checked",true).next('span').attr("style","box-shadow: rgb(38, 185, 154) 0px 0px 0px 16px inset; border-color: rgb(38, 185, 154); background-color: rgb(38, 185, 154); transition: border 0.4s, box-shadow 0.4s, background-color 1.2s;").find('small').attr("style","left: "+l[c]+"; transition: background-color 0.4s, left 0.2s; background-color: rgb(255, 255, 255);");
    }else if ( check.checked && !active ){
        $(check).prop("checked",false).next('span').attr("style","box-shadow: rgb(223, 223, 223) 0px 0px 0px 0px inset; border-color: rgb(223, 223, 223); background-color: rgb(255, 255, 255); transition: border 0.4s, box-shadow 0.4s;").find('small').attr("style","left: 0px; transition: background-color 0.4s, left 0.2s;");
    }
}

changeSwitch(".js-switch",true);

如果您想重置表单,请在使用之前执行以下操作:

changeSwitch(".js-switch",true);
$("#frm_id").trigger("reset");

2

3
谢谢。当我在控制台运行它以更改状态时,它对我没有动态作用。 - Liron Harel
它不起作用是因为您在初始化插件之前更改了状态。问题是,如何在初始化后更改状态。 - Filip Kováč

2

综合几个答案,适用于v0.8.2。

    function setSwitchery(switchElement, checkedBool) {
        if (checkedBool && !switchElement.checked) { // switch on if not on
            $(switchElement).trigger('click').attr("checked", "checked");
        } else if (!checkedBool && switchElement.checked) { // switch off if not off
            $(switchElement).trigger('click').removeAttr("checked");
        }
    }

示例用法:

var switchElement = $('#mySwitchInput');
setSwitchery(switchElement, false);

(!switchElement.checked)的效果不佳。在我的情况下,我使用(! switchElement.is(':checked'))解决了这个问题。 - MSA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接