King
King

Reputation: 53

Select2.js not working in dropdown

I Am using Select2.js ,KnockoutJs,Durandal 2.0

var ViewModel =
    [
        { id: "AL", text: "Alabama" },
        { id: "AK", text: "Alaska" },
        { id: "AZ", text: "Arizona" },
        { id: "AR", text: "Arkansas" },
        { id: "CA", text: "California" },
        { id: "CO", text: "Colorado" }
    ]
var stateQuery = function (query) {

    var states = [];
    ko.utils.arrayForEach(states, function (state) {
        if (state.text.search(new RegExp(query.term, 'i')) >= 0) {
            states.push(state);
    }
    });

While Binding in drop down it is working fine.But if i change text to Text_Name i am getting can not convert to upperCase of undefined.

var ViewModel =
    [
        { id: "AL", Text_Name: "Alabama" },
        { id: "AK", Text_Name: "Alaska" },
        { id: "AZ", Text_Name: "Arizona" },
        { id: "AR", Text_Name: "Arkansas" },
        { id: "CA", Text_Name: "California" },
        { id: "CO", Text_Name: "Colorado" }
    ]

Upvotes: 1

Views: 1037

Answers (1)

margabit
margabit

Reputation: 2954

It's a select2 convention. See the documentation:

The default implementation expects the object to have a text property that is returned.

To change this behaviour you should specify the functions formatResult and formatSelection and specify the new text property:

function format(item) {
    return item.Text_Name
}

If you are using a Knockout binding handler:

<select data-bind="options: states, optionsValue: 'id', optionsText: 'text', value: states, select2: { formatSelection: format, formatResult: format  }"></select>

Upvotes: 1

Related Questions