Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

javascript - Select2 4.0 - Push new entry after creation

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.

Within the dropdown list, I have the choice to

  • select an entry in the list (using ajax)
  • add a free entry (using createTag)
  • add a new entry

If I select "add a new entry", I can fill out a form, and once saved, the new data must be shown as a selected entry.

If I push data using select2_existing.select2( { data: data } ).val( 4 ); it works, but ajax call does not work anymore.

I have then to

  1. destroy select2
  2. re-create it

Which will then allow me to have my new data and ajax adapter working.

It is possible to do this without the create->data->destroy->create cycle?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...