首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在页面初始化时禁用jQuery ComboBox。根据[邮政编码]组合框的值重新启用[StreetName]组合框

在页面初始化时禁用jQuery ComboBox。根据[邮政编码]组合框的值重新启用[StreetName]组合框
EN

Stack Overflow用户
提问于 2019-10-16 15:40:20
回答 1查看 24关注 0票数 0

我试图在我的网页上有4 ComboBoxes。

当页面加载初始化时,只能启用一个邮政编码组合框,并且必须禁用所有的StreetName、郊区和州。

现在,当我从Postcode combobox元素的自动完成下拉列表中选择一个有效值时,我只希望街名combobox被启用。

类似地,当我从StreetName combobox元素的自动完成下拉列表中选择一个有效值时,我希望仅启用郊区combobox。同样,国家组合框的情况也是如此。

到目前为止,我已经修改了AutoComplete ComboBox在jQuery网站(https://jqueryui.com/autocomplete/#combobox)上已经可用的代码。

我还为我的combobox.js文件和cshtml文件粘贴下面的代码。

combobox.js

代码语言:javascript
复制
$(function () {
    $.widget("custom.combobox", {
        options: {
            source: function (request, response) { console.error('source not defined') },
            select: function (event, ui) { },
            change: function (event, ui) { },
            showTitleForAllItems: true,
            showAllTitleText: 'Show All Items'
        },
        _cache: [],
        _create: function () {
            this.wrapper = $("<span>")
              .addClass("custom-combobox")
              .insertAfter(this.element);

            this.element.hide();
            this._createAutocomplete();
            this._createShowAllButton();
        },

        _createAutocomplete: function () {
            var selected = this.element.children(":selected"),
              value = selected.val() ? selected.text() : "";

               this.input = $("<input>")
              .appendTo(this.wrapper)
              .val(value)
              .attr("title", "")
              .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
              .autocomplete({
                  delay: 0,
                  minLength: 0,
                  source: $.proxy(this, "_source")
              })
              .tooltip({
                  classes: {
                      "ui-tooltip": "ui-state-highlight"
                  }
              });

            this._on(this.input, {
                autocompleteselect: function (event, ui) {
                    //ui.item.value.selected = true;
                    this._trigger("select", event, {
                        item: ui.item.value
                    });
                },

                autocompletechange: "_removeIfInvalid"
            });
        },

        _createShowAllButton: function () {
            var input = this.input,
              wasOpen = false;

            $("<a>")
              .attr("tabIndex", -1)
              .attr("title", "Show All Items")
              .tooltip()
              .appendTo(this.wrapper)
              .button({
                  icons: {
                      primary: "ui-icon-triangle-1-s"
                  },
                  text: false
              })
              .removeClass("ui-corner-all")
              .addClass("custom-combobox-toggle ui-corner-right")
              .on("mousedown", function () {
                  wasOpen = input.autocomplete("widget").is(":visible");
              })
              .on("click", function () {
                  input.trigger("focus");

                  // Close if already visible
                  if (wasOpen) {
                      return;
                  }

                  // Pass empty string as value to search for, displaying all results
                  input.autocomplete("search", "");
              });
        },

        _source: function (request, response) {
            var that = this;
            var data = this.options.source(request, function (data) {

                that._cache = that._cache.concat(data);
                response(data)
            });

        },

        _removeIfInvalid: function (event, ui) {

            // Selected an item, nothing to do
            if (ui.item)
            {
                this.options.change(event, ui);
                return;
            }

            // Search for a match (case-insensitive)
            var value = this.input.val(),
              valueLowerCase = value.toLowerCase(),
              valid = false;
            this._cache.forEach(function (item) {
                if (item.toLowerCase() === valueLowerCase) {
                    this.selected = valid = true;
                    return false;
                }
            });

            // Found a match, nothing to do
            if (valid)
            {
                //this.options.change(event, ui);
                return;
            }

            // Remove invalid value
            this.input
              .val("")
              .attr("title", value + " didn't match any item")
              .tooltip("open");
            this.element.val("");
            this._delay(function () {
                this.input.tooltip("close").attr("title", "");
            }, 2500);
            this.input.autocomplete("instance").term = "";
        },

        _destroy: function () {
            this.wrapper.remove();
            this.element.show();
        }
});

});

cshtml

代码语言:javascript
复制
<div class="shipping-information-block-right">
            <div class="shopping-cart-cehckout-form-left-inner-right">
                Postcode:<br>
                <input type="text" id="Postcode" name="Postcode">
            </div>
            <div class="clearfix"></div>
            <div class="shopping-cart-cehckout-form-left-inner-left">
                @*<label>Street Name<span class="red-star">*</span></label>*@
            </div>
            <div class="shopping-cart-cehckout-form-left-inner-right">
                Street Name:<br>
                <input type="text" id="StreetName" name="StreetName">
                <br><br>
            </div>
            <div class="clearfix"></div>
            <div class="shopping-cart-cehckout-form-left-inner-left">
                @*<label>Suburb<span class="red-star">*</span></label>*@
            </div>
            <div class="shopping-cart-cehckout-form-left-inner-right">
                Suburb<br>
                <input type="text" id="Suburb" name="Suburb">
                <br><br>
            </div>
            <div class="clearfix"></div>

            <div class="shopping-cart-cehckout-form-left-inner-left">
                @*<label>State<span class="red-star">*</span></label>*@
            </div>
            <div class="shopping-cart-cehckout-form-left-inner-right">
                State:<br>
                <input type="text" id="State" name="State">
                <br><br>
            </div>

        </div>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
    $(document).ready(function () {
        $('#StreetName').attr("disabled", "disabled");
        $('#Suburb').attr("disabled", "disabled");
        $('#State').attr("disabled", "disabled");

        $('#Postcode').combobox({
            source: function (request, response) {
                debugger;
                var data = [];
                $.ajax({
                    url: "/en/B2B/Menu/Online-Shop/Online-Payment/Shipping/GetAddressDetails",
                    dataType: "json",
                    data: {
                        PostCode: request.term
                    },
                    success: function (data) {
                        //$.each(data.Entity, function(index, value) {
                        //    temporary[i++] = value.PostCode;
                        //})
                        //dbData = jQuery.unique(temporary);
                        var data = $.map(data.Entity, function (item) {
                            return item.PostCode;
                        });
                        response(data);
                        debugger;
                    },
                    error: function (error) {
                        debugger;
                    }
                });

            },
            change: function (event, ui) {
                if (ui.item == null) {
                    debugger;
                    $('#StreetName').attr("disabled", "disabled");
                }
                else
                {
                    debugger;
                    $(function () {
                        $('#StreetName').removeAttr("disabled");
                    });
                }
            }
        });
        if ($('#StreetName').attr("disabled", "disabled")) {
            debugger;
            $("#StreetName").closest(".ui-widget").find("input, button").prop("disabled", true);
        }
        else {
            $('#StreetName').combobox({
                disabled: true,
                source: function (request, response) {
                    debugger;
                    var data = [];
                    $.ajax({
                        url: "/en/B2B/Menu/Online-Shop/Online-Payment/Shipping/GetAddressDetails",
                        dataType: "json",
                        data: {
                            StreetName: request.term
                        },
                        success: function (data) {
                            //$.each(data.Entity, function(index, value) {
                            //    temporary[i++] = value.PostCode;
                            //})
                            //dbData = jQuery.unique(temporary);
                            var data = $.map(data.Entity, function (item) {
                                return item.StreetName;
                            });
                            response(data);
                            debugger;
                        },
                        error: function (error) {
                            debugger;
                        }
                    });

                }
            });
        }

        if ($('#Suburb').attr("disabled", "disabled")) {
            debugger;
            $("#Suburb").closest(".ui-widget").find("input, button").prop("disabled", true);
        }
        else {
            $('#Suburb').combobox({
                source: function (request, response) {
                    debugger;
                    var data = [];
                    $.ajax({
                        url: "/en/B2B/Menu/Online-Shop/Online-Payment/Shipping/GetAddressDetails",
                        dataType: "json",
                        data: {
                            Suburb: request.term
                        },
                        success: function (data) {
                            //$.each(data.Entity, function(index, value) {
                            //    temporary[i++] = value.PostCode;
                            //})
                            //dbData = jQuery.unique(temporary);
                            var data = $.map(data.Entity, function (item) {
                                return item.Suburb;
                            });
                            response(data);
                            debugger;
                        },
                        error: function (error) {
                            debugger;
                        }
                    });

                }
            });
        }
        if ($('#State').attr("disabled", "disabled")) {
            debugger;
            $("#State").parent().find("input.ui-autocomplete-input").autocomplete("option", "disabled", true).prop("disabled", true);
            $("#State").parent().find("a.ui-button").button("disable");
        }
        else {
            $('#State').combobox({
                source: function (request, response) {
                    debugger;
                    var data = [];
                    $.ajax({
                        url: "/en/B2B/Menu/Online-Shop/Online-Payment/Shipping/GetAddressDetails",
                        dataType: "json",
                        data: {
                            State: request.term
                        },
                        success: function (data) {
                            //$.each(data.Entity, function(index, value) {
                            //    temporary[i++] = value.PostCode;
                            //})
                            //dbData = jQuery.unique(temporary);
                            var data = $.map(data.Entity, function (item) {
                                return item.State;
                            });
                            response(data);
                            debugger;
                        },
                        error: function (error) {
                            debugger;
                        }
                    });

                }
            });
        }
    });
</script>
EN

回答 1

Stack Overflow用户

发布于 2019-10-17 07:23:35

我特此提及我在这两个文件的代码中所做的更改,以实现预期的功能。我希望这能帮助那些正在寻找类似功能的人。

cshtml文件

所有的组合框都是这样的,除了邮政编码组合框。在邮政编码中,启用Combobox设置为true,因为在加载页面时需要这样做。

代码语言:javascript
复制
$('#StreetName').combobox({
            enabled: false,
                source: function (request, response) {
                    debugger;
                    var data = [];
                    $.ajax({
                        url: "/en/B2B/Menu/Online-Shop/Online-Payment/Shipping/GetAddressDetails",
                        dataType: "json",
                        data: {
                            StreetName: request.term
                        },
                        success: function (data) {
                            //$.each(data.Entity, function(index, value) {
                            //    temporary[i++] = value.PostCode;
                            //})
                            //dbData = jQuery.unique(temporary);
                            var data = $.map(data.Entity, function (item) {
                                return item.StreetName;
                            });
                            response(data);
                            debugger;
                        },
                        error: function (error) {
                            debugger;
                        }
                    });

                },
                change: function (event, ui) {

                    if (ui.item == null) {
                        debugger;
                        $("#Suburb").combobox("toggleState", false);
                    }
                    else {
                        debugger;
                        $("#Suburb").combobox("toggleState", true);
                    }
                },
                change: function (valid) {
                    if (valid) {
                        $("#Suburb").combobox("toggleState", true);
                    }
                    else {
                        $("#Suburb").combobox("toggleState", false);
                    }
                }
            });

在combobox.js库文件中,我修改了选项、创建函数以及它处理无效值的部分,请参阅参考。

combobox.js

代码语言:javascript
复制
$(function () {
    $.widget("custom.combobox", {
        options: {
            source: function (request, response) { console.error('source not defined') },
            select: function (event, ui) { },
            change: function (event, ui) { },
            change: function (valid) { },
            enabled: true, 
            showTitleForAllItems: true,
            showAllTitleText: 'Show All Items',
        },
        toggleState: function (state) {
            if(state)
            {
                this.input.prop('disabled', false);
                this.input.autocomplete("enable");
                this.a.prop("enable");
            }
            else
            {
                this.input.prop('disabled', true);
                this.input.autocomplete("disable");
                this.a.prop("disable");
            }
        },
        _cache: [],
        _create: function () {
            this.wrapper = $("<span>")
              .addClass("custom-combobox")
              .insertAfter(this.element);

            this.element.hide();
            this._createAutocomplete();
            this._createShowAllButton();
            this._enabled();
        },

        _enabled: function ()
        {
            if (this.options.enabled)
            {
                this.toggleState(true);
            }
            else
            {
                this.toggleState(false);
            }
        },

        _createAutocomplete: function () {
            var selected = this.element.children(":selected"),
              value = selected.val() ? selected.text() : "";

               this.input = $("<input>")
              .appendTo(this.wrapper)
              .val(value)
              .attr("title", "")
              .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
              .autocomplete({
                  delay: 0,
                  minLength: 0,
                  source: $.proxy(this, "_source")
              })
              .tooltip({
                  classes: {
                      "ui-tooltip": "ui-state-highlight"
                  }
              });

            this._on(this.input, {
                autocompleteselect: function (event, ui) {
                    //ui.item.value.selected = true;
                    this._trigger("select", event, {
                        item: ui.item.value
                    });
                },

                autocompletechange: "_removeIfInvalid"
            });
        },

        _createShowAllButton: function () {
            var input = this.input,
              wasOpen = false;
            this.a = $("<a>").attr("tabIndex", -1);
            if (this.options.showTitleForAllItems) {
                btn = $(this.a)
                .attr("title", this.options.showAllTitleText)
              .tooltip()
            }
            $(this.a)
              .appendTo(this.wrapper)
              .button({
                  icons: {
                      primary: "ui-icon-triangle-1-s"
                  },
                  text: false
              })
              .removeClass("ui-corner-all")
              .addClass("custom-combobox-toggle ui-corner-right")
              .on("mousedown", function () {
                  wasOpen = input.autocomplete("widget").is(":visible");
              })
              .on("click", function () {
                  input.trigger("focus");

                  // Close if already visible
                  if (wasOpen) {
                      return;
                  }

                  // Pass empty string as value to search for, displaying all results
                  input.autocomplete("search", "");
              });
        },

        _source: function (request, response) {
            var that = this;
            var data = this.options.source(request, function (data) {

                that._cache = that._cache.concat(data);
                response(data)
            });

        },

        _removeIfInvalid: function (event, ui) {

            // Selected an item, nothing to do
            if (ui.item)
            {
                this.options.change(event, ui);
                return;
            }

            // Search for a match (case-insensitive)
            var value = this.input.val(),
              valueLowerCase = value.toLowerCase(),
              valid = false;
            this._cache.forEach(function (item) {
                if (item.toLowerCase() === valueLowerCase) {
                    this.selected = valid = true;
                    return false;
                }
            });

            // Found a match, nothing to do
            if (valid)
            {
                this.options.change(valid);
                return;
            }
            else
            {
                this.options.change(valid);
            }

            // Remove invalid value
            this.input
              .val("")
              .attr("title", value + " didn't match any item")
              .tooltip("open");
            this.element.val("");
            this._delay(function () {
                this.input.tooltip("close").attr("title", "");
            }, 2500);
            this.input.autocomplete("instance").term = "";
        },

        _destroy: function () {
            this.wrapper.remove();
            this.element.show();
        }
    });

});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58417072

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档