Select2 4.0 - Push new entry after creation

后端 未结 1 1185
失恋的感觉
失恋的感觉 2020-12-01 19:49

I have been using Select2 4.0.0-rc.1 for a couple of weeks (using the ajax adapter) and I am trying to find a way to \"push\" data after it has been initialized

相关标签:
1条回答
  • 2020-12-01 20:22

    You should be able to push a new selected option by creating a new <option selected> tag with the information you are looking to display.

    <option value="id" selected="selected">text</option>
    

    Once you append this <option> to the original <select>, you are going to need to trigger the change event so Select2 (and other components) are aware that the value changed.

    $element.trigger("change");
    

    So putting it all together in JavaScript

    var $element = $("select"); // the element that Select2 is initialized on
    
    var $option = $("<option selected></option>"); // the new base option
    $option.val(newOption.id); // set the id
    $option.text(newOption.text); // set the text
    
    $element.append($option); // add it to the list of selections
    $element.trigger("change"); // tell Select2 to update
    
    0 讨论(0)
提交回复
热议问题