Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set selected value of jQuery Select2?

This belong to codes prior to Select2 version 4

I have a simple code of select2 that get data from AJAX.

$("#programid").select2({
  placeholder: "Select a Program",
  allowClear: true,
  minimumInputLength: 3,
  ajax: {
    url: "ajax.php",
    dataType: 'json',
    quietMillis: 200,
    data: function (term, page) {
      return {
        term: term, //search term
        flag: 'selectprogram',
        page: page // page number
      };
    },
    results: function (data) {
      return {results: data};
    }
  },
  dropdownCssClass: "bigdrop",
  escapeMarkup: function (m) { return m; }
});

This code is working, however, I need to set a value on it as if in edit mode. When user select a value first time, it will be saved and when he needs to edit that value it must appear in the same select menu (select2) to select the value previously selected but I can't find a way.

UPDATE:

The HTML code:

<input type="hidden" name="programid" id="programid" class="width-500 validate[required]">

Select2 programmatic access does not work with this.

like image 909
ClearBoth Avatar asked Aug 07 '14 16:08

ClearBoth


People also ask

How do I set Select2 values?

To set selected value of jQuery Select2 with JavaScript, we call val and then trigger . Then we set its value with val to the option with value 0. Finally, we call trigger with 'change' to update the drop down to show the value we set.

How do I select a specific Dropdownlist using jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).

How do I add options to a Dropdownlist using jQuery?

Method 1: Append the option tag to the select box The option to be added is created like a normal HTML string. The select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection.

How do I add options in Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).


2 Answers

SELECT2 < V4


Step #1: HTML

<input name="mySelect2" type="hidden" id="mySelect2">

Step #2: Create an instance of Select2

$("#mySelect2").select2({
      placeholder: "My Select 2",
      multiple: false,
      minimumInputLength: 1,
      ajax: {
          url: "/elements/all",
          dataType: 'json',
          quietMillis: 250,
          data: function(term, page) {
              return {
                  q: term,
              };
          },
          results: function(data, page) {
              return {results: data};
          },
          cache: true
      },
      formatResult: function(element){
          return element.text + ' (' + element.id + ')';
      },
      formatSelection: function(element){
          return element.text + ' (' + element.id + ')';
      },
      escapeMarkup: function(m) {
          return m;
      }
});

Step #3: Set your desired value

$("#mySelect2").select2('data', { id:"elementID", text: "Hello!"});

If you use select2 without AJAX you can do as follow:

<select name="mySelect2" id="mySelect2">
  <option value="0">One</option>
  <option value="1">Two</option>
  <option value="2">Three</option>
</select>
/* "One" will be the selected option */
$('[name=mySelect2]').val("0");

You can also do so:

$("#mySelect2").select2("val", "0");

SELECT2 V4


For select2 v4 you can append directly an option/s as follow:

<select id="myMultipleSelect2" multiple="" name="myMultipleSelect2[]">
    <option value="TheID" selected="selected">The text</option>                                                                   
</select>

Or with JQuery:

var $newOption = $("<option selected='selected'></option>").val("TheID").text("The text")
 
$("#myMultipleSelect2").append($newOption).trigger('change');

other example

$("#myMultipleSelect2").val(5).trigger('change');
like image 56
tomloprod Avatar answered Oct 13 '22 22:10

tomloprod


To dynamically set the "selected" value of a Select2 component:

$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});

Where the second parameter is an object with expected values.

UPDATE:

This does work, just wanted to note that in the new select2, "a_key" is "text" in a standard select2 object. so: {id: 100, text: 'Lorem Ipsum'}

Example:

$('#all_contacts').select2('data', {id: '123', text: 'res_data.primary_email'});

Thanks to @NoobishPro

like image 21
An Phan Avatar answered Oct 14 '22 00:10

An Phan