Unable to select a result from the select2 search results

后端 未结 4 953
庸人自扰
庸人自扰 2020-12-06 11:05

I am using the select2 for on of my search boxes. I\'m getting the results from my URL but I\'m not able to select an option from it. I want to use the \'product.productName

相关标签:
4条回答
  • 2020-12-06 11:13

    You are missing id attribute for result data. if it has not, it makes option "unselectable".

    Example:

                $('#e7').select2({
                        id: function(e) { return e.productName; },
                });
    
    0 讨论(0)
  • 2020-12-06 11:13

    Since I was using AJAX, what worked for me was returning something as the ID on processResults:

    $(field).select2({
       ajax: {
            // [..] ajax params here
            processResults: function(data) {
                return {
                    results: $.map(data, function(item) {
                        return {
                            // proccessResults NEEDS the attribute id here
                            id: item.code,
                            // [...] other attributes here
                            foo: item.bar,
                        }
                    })
                }
            },
        },
    });
    
    0 讨论(0)
  • 2020-12-06 11:14

    I have faced the same issue,other solution for this issue is:-

    In your response object(In above response Product details object) must have an "id" as key and value for that.

    Example:- Your above given response object must be like this

    {"id":"1","productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"}

    SO you don't need this id: function(object){return object.key;}

    0 讨论(0)
  • 2020-12-06 11:18

    The id param can be a string related to the object property name, and must be in the root of the object. Text inside data object.

    var fruits = [{code: 222, fruit: 'grape', color:'purple', price: 2.2},
      {code: 234,fruit: 'banana', color:'yellow', price: 1.9} ];
    
    $(yourfield).select2(
     {
       id: 'code',
       data: { results: fruits, text: 'fruit' }
     }
    );
    
    0 讨论(0)
提交回复
热议问题