JQuery autocomplete how to write label in autocomplete text input?

前端 未结 5 1919
花落未央
花落未央 2020-12-18 05:57

Hello I am using jQuery UI autocomplete.

I am getting values and labels from the drop down area. I will write the value in a hidden input and use it later. I could d

5条回答
  •  死守一世寂寞
    2020-12-18 06:33

    A tiny plugin for a general purpose solution:

    (function($) {
        $.fn.autocompleteHidden = function($hiddenInput, autocompleteOpts) {
            if ('string' == typeof $hiddenInput) {
                $hiddenInput = $($hiddenInput);
            }
            var $input = this;
            var opts = $.extend({}, autocompleteOpts, {
                focus: function(evt, ui) {
                    $input.val(ui.item.label);
                    if (autocompleteOpts.focus) {
                        autocompleteOpts.focus.apply(this, arguments);
                    }
                    return false;
                }
                , select: function(evt, ui) {
                    $hiddenInput.val(ui.item.value);
                    $input.val(ui.item.label);
                    if (autocompleteOpts.select) {
                        autocompleteOpts.select.apply(this, arguments);
                    }
                    return false;
                }
            });
            this.autocomplete(opts);
            $input.change(function(evt) {
                if (/^\s*$/.test(this.value)) {
                    $hiddenInput.val('');
                }
            });
        };
    })(jQuery);
    

    So where you'd use yourInput.autocomplete(options), you instead use yourInput.autocompleteHidden(selectorOrJqueryObject, options). This has the benefit of still allowing additional focus and select options, without repeated code. It also clears the hidden input when no (visible) value is entered in the main input.

提交回复
热议问题