How to set Default Value in tagging in select2 jquery

前端 未结 3 1111
长情又很酷
长情又很酷 2021-01-12 16:45

I am using select2 (http://ivaynberg.github.io/select2/) for my tagging input. from the example in using select2 tagging the code is look like this.

 $(\"#e1         


        
相关标签:
3条回答
  • 2021-01-12 17:20

    For Select2 4.0 I had to add the data attribute to select2 and also set value and trigger change, like this:

    $('#mySelect').select2({
      data: ['one','two'],
      tags: true
    });
    $('#mySelect').val(['one','two']).trigger('change')
    
    0 讨论(0)
  • 2021-01-12 17:25

    Updated version

    Say you initialized your select like this:

    $('.mySelect').select2({
      multiple: true,
      tags: "true"
    });
    

    Then use this 2 functions for triggering the change. (as seen in the official documentation)

    $('.mySelect').val(['value1', 'value2']);
    $('.mySelect').trigger('change.select2');
    

    Where "value1" and "value2" are IDs of the option elements of the select.

    0 讨论(0)
  • 2021-01-12 17:35

    You can initialize the Select2 control by providing a value for the hidden input:

    <input type="hidden" id="e12" value="brown,red,green" />
    

    And you can set the value of the Select2 control by passing an array to the 'val' method:

    $('#tagSelect').select2('val', ['brown','red','green']);
    

    jsfiddle demo

    0 讨论(0)
提交回复
热议问题