Bootstrap 如何检测引导多重选择中的变化

bfnvny8b  于 2022-12-07  发布在  Bootstrap
关注(0)|答案(2)|浏览(158)

Is it possible to detect whether there have been any changes in a Bootstrap Muiltiselcts options upon closing the dropdown. I want to use the onDropdownHidden event documented here on the authors docs page: onDropDownHidden Event to allow me to see if the user has de-selected or selected anything since the drop down was opened. Upon opening the multi-select will have some pre-selected options. I need to know (especially) whether they have toggled an option (thus no change to initial selections) so i can decide whether to call a function to initiate saving the new changes. I want to avoid just calling this function after an onChange of an option if the resultant state is the same. Its similar to isDirty used to check if any control on a form has been edited - is there some similar technique for Multi-select??
Thanks.

frebpwbc

frebpwbc1#

那么多重选择是否设置了默认值呢?这些选择是否只在更新/向数据库添加内容时使用呢?
我真的不知道你是想使用javascript还是PHP,但是如果你使用PHP,检查if isset($multiselectfield){}有意义吗?
或者更简单地说,如果它有默认值,则检查if ($multiselectfield != defaultvalue) {}。如果它不是默认值,则检查if ($multiselectfield != defaultvalue) {},否则默认值一定是被忽略的。
只是我的想法,但问题的措辞不太恰当,无法给予你一个充分的答案。我只是尝试一下。

vu8f3i0k

vu8f3i0k2#

对于JS和JQuery用户的

我就是这样解决这个问题的。

/*
 * This variable will be used to track whether:
 * The selected values for the dropdown before opening it is same while closing or not.
 * Reason behind tracking?
 * If user just opened and closed the dropdown without selecting or deselecting the options,
 * the handler assigned to onDropdownHide event will be fired that is not expected.
 */
let monthValueBeforeDropdownShown;

// This function simply capture the selected options
// and put it in the variable
function captureValuesBeforeDropdownShown() {
    monthValueBeforeDropdownShown = $("#drop-down-id").val();
}

$("#drop-down-id").multiselect({
    onDropdownShow: captureValuesBeforeDropdownShown,
    onDropdownHide: exitMonthChangeHandler
});

function exitMonthChangeHandler() {
    // If no values are present (nothing selected) we'll terminate
    if(!$("#drop-down-id").val().length) return;

    // Comparing the dropdown values before opening and after closing.
    // If there is no change we'll terminate
    if (monthValueBeforeDropdownShown.toString() === $("#drop-down-id").val().toString()) return;

    // HERE YOU CAN WRITE YOUR AJAX OR WHATEVER LOGIC YOU WANT
}

PS:仍然有一些余量,以优化这个代码利用现代JS高阶函数。

相关问题