dianping/cat · error · Error

val() cannot be called if initSelection() is not defined

Error message

val() cannot be called if initSelection() is not defined

What it means

Error "val() cannot be called if initSelection() is not defined" thrown in dianping/cat.

Source

Thrown at cat-home/src/main/webapp/assets/js/uncompressed/select2.js:3259

                this.updateSelection([]);
                this.clearSearch();
                if (triggerChange) {
                    this.triggerChange({added: this.data(), removed: oldData});
                }
                return;
            }

            // val is a list of ids
            this.setVal(val);

            if (this.select) {
                this.opts.initSelection(this.select, this.bind(this.updateSelection));
                if (triggerChange) {
                    this.triggerChange(this.buildChangeDetails(oldData, this.data()));
                }
            } else {
                if (this.opts.initSelection === undefined) {
                    throw new Error("val() cannot be called if initSelection() is not defined");
                }

                this.opts.initSelection(this.opts.element, function(data){
                    var ids=$.map(data, self.id);
                    self.setVal(ids);
                    self.updateSelection(data);
                    self.clearSearch();
                    if (triggerChange) {
                        self.triggerChange(self.buildChangeDetails(oldData, self.data()));
                    }
                });
            }
            this.clearSearch();
        },

        // multi
        onSortStart: function() {
            if (this.select) {

View on GitHub (pinned to e815e74d4c)

Solutions

  1. Define the initSelection option when attaching Select2 to a hidden input so val() can resolve ids to data.
  2. Set data via select2('data', ...) instead of relying on val().

When it happens

Trigger: Triggered when val() is called on a Select2 attached to an <input type='hidden'> without defining initSelection() to map ids to objects.

Common situations: See trigger scenarios.


AI-assisted analysis of dianping/cat@e815e74d4c (2026-08-14). Data as JSON: /api/errors/26b734aca720dc36. Report an issue: GitHub.