【问题标题】:Do not show options in selectbox after max options using jquery在使用 jquery 的最大选项之后不要在选择框中显示选项
【发布时间】:2021-03-25 10:47:44
【问题描述】:

我有以下代码:

$( "#multipleOptions" ).change(function() {
    if (this.selectedOptions.length <= 3) {
        var multipleOptions = [0];
        if ($(this).val()){
            multipleOptions = $(this).val();
        }
        var postData = { "multipleOptions": multipleOptions }
        $.ajax(url = "/app/"+multipleOptionsId+"/",
            type="PATCH",
            data=postData,
            success=function(resp){
                notify("Multiple Options update was successful", "success");
            },
            error=function(){
                alert("Could not save", "error");
            }
        );
    } else {
        alert("You can only select a maximum of three options");
    }
});

这里我需要将选项的数量限制为三个。现在从我所写的内容来看,它不会向后端发送超过三个的选项,但问题是如果在选择框中选择超过三个选项,它将显示额外的选项以及警报消息。如何不显示额外选项而只显示警报消息?

【问题讨论】:

  • change 发生在 值更改之后,因此您无法取消它们。当&lt;=3 然后&gt;3 恢复这些值时,您可以改为“存储”当前值
  • 好的。谢谢。明白了。

标签: javascript jquery


【解决方案1】:

根据@freedomn-m 的评论,这就是我的工作方式:

var multipleOptionsVar;

$( "#multipleOptions" ).change(function() {
    if (this.selectedOptions.length <= 3) {
        var multipleOptions = [0];
        if ($(this).val()){
            multipleOptions = $(this).val();
            multipleOptionsVar = multipleOptions;
        }
        var postData = { "multipleOptions": multipleOptions }
        $.ajax(url = "/app/"+multipleOptionsId+"/",
            type="PATCH",
            data=postData,
            success=function(resp){
                notify("Multiple Options update was successful", "success");
            },
            error=function(){
                alert("Could not save", "error");
            }
        );
    } else {
        $(this).val(multipleOptionsVar);
        $(this).trigger("change.select2");
        alert("You can only select a maximum of three options");
    }
});

window.onload = function(e) {
    multipleOptionsVar = $( "#multipleOptions" ).val();
}

【讨论】:

    猜你喜欢
    • 2012-12-17
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 2021-11-07
    • 2014-11-22
    • 2019-11-17
    相关资源
    最近更新 更多