How to set selected value of jquery select2?

后端 未结 28 1433
野趣味
野趣味 2020-11-30 00:00

This belong to codes prior to select2 version 4

I have a simple code of select2 that get data from ajax



        
28条回答
  •  半阙折子戏
    2020-11-30 00:39

    SELECT2 < V4


    Step #1: HTML

    
    

    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:

    
    
    /* "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:

    
    

    Or with JQuery:

    var $newOption = $("").val("TheID").text("The text")
     
    $("#myMultipleSelect2").append($newOption).trigger('change');
    

    other example

    $("#myMultipleSelect2").val(5).trigger('change');
    

提交回复
热议问题