How to set selected value of jquery select2?

后端 未结 28 1130
野趣味
野趣味 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:36

    To build ontop of @tomloprod's answer. By the odd chance that you are using x-editable, and have a select2(v4) field and have multiple items you need to pre-select. You can use the following piece of code:

    $("#select2field").on("shown", function(e, editable){
        $(["test1", "test2", "test3", "test4"]).each(function(k, v){
            // Create a DOM Option and pre-select by default~
            var newOption = new Option(v.text, v.id, true, true);
            // Append it to the select
            $(editable.input.$input).append(newOption).trigger('change');
         });
    });
    

    and here it is in action:

    var data = [
    {
        id: 0,
        text: 'enhancement'
    },
    {
        id: 1,
        text: 'bug'
    },
    {
        id: 2,
        text: 'duplicate'
    },
    {
        id: 3,
        text: 'invalid'
    },
    {
        id: 4,
        text: 'wontfix'
    }
    ];
    
    $("#select2field").editable({
            type: "select2",
            url: './',
            name: 'select2field',
            savenochange: true,
            send: 'always',
            mode: 'inline',
            source: data,
            value: "bug, wontfix",
            tpl: '<select style="width: 201px;">',
            select2: {
                width: '201px',
                tags: true,
                tokenSeparators: [',', ' '],
                multiple: true,
                data:data
            },
            success: function(response, newValue) {
                console.log("success")
            },
            error: function(response, newValue) {
                if (response.status === 500) {
                    return 'Service unavailable. Please try later.';
                } else {
                    return response.responseJSON;
                }
            }
        });
    
    var preselect= [
        {
            id: 1,
            text: 'bug'
        },
        {
        id: 4,
        text: 'wontfix'
    }
    ];
    
     $("#select2field").on("shown", function(e, editable){
        $(preselect).each(function(k, v){
            // Create a DOM Option and pre-select by default~
            var newOption = new Option(v.text, v.id, true, true);
            // Append it to the select
            $(editable.input.$input).append(newOption).trigger('change');
         });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
    <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
    
    <link href="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"/>
    <script src="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/js/bootstrap-editable.min.js"></script>
    
    <a id="select2field">bug, wontfix</a>

    I guess that this would work even if you aren't using x-editable. I hope that htis could help someone.

    0 讨论(0)
  • 2020-11-30 00:36

    You can use this code:

        $('#country').select2("val", "Your_value").trigger('change');
    

    Put your desired value instead of Your_value

    Hope It will work :)

    0 讨论(0)
  • 2020-11-30 00:38

    In the current version on select2 - v4.0.1 you can set the value like this:

    var $example = $('.js-example-programmatic').select2();
    $(".js-programmatic-set-val").on("click", function () { $example.val("CA").trigger("change"); });
    
    // Option 2 if you can't trigger the change event.
    var $exampleDestroy = $('.js-example-programmatic-destroy').select2();
    $(".js-programmatic-set-val").on("click", function () { $exampleDestroy.val("CA").select2('destroy').select2(); });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
    <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
    
    using "trigger(change)"
    <select class="js-example-programmatic">
      <optgroup label="Alaskan/Hawaiian Time Zone">
        <option value="AK">Alaska</option>
        <option value="HI">Hawaii</option>
      </optgroup>
      <optgroup label="Pacific Time Zone">
        <option value="CA">California</option>
        <option value="NV">Nevada</option>
        <option value="OR">Oregon</option>
        <option value="WA">Washington</option>
      </optgroup>
      <optgroup label="Mountain Time Zone">
        <option value="AZ">Arizona</option>
        <option value="CO">Colorado</option>
        <option value="ID">Idaho</option>
        <option value="MT">Montana</option>
        <option value="NE">Nebraska</option>
        <option value="NM">New Mexico</option>
        <option value="ND">North Dakota</option>
        <option value="UT">Utah</option>
        <option value="WY">Wyoming</option>
      </optgroup>
      <optgroup label="Central Time Zone">
        <option value="AL">Alabama</option>
        <option value="AR">Arkansas</option>
        <option value="IL">Illinois</option>
        <option value="IA">Iowa</option>
        <option value="KS">Kansas</option>
        <option value="KY">Kentucky</option>
        <option value="LA">Louisiana</option>
        <option value="MN">Minnesota</option>
        <option value="MS">Mississippi</option>
        <option value="MO">Missouri</option>
        <option value="OK">Oklahoma</option>
        <option value="SD">South Dakota</option>
        <option value="TX">Texas</option>
        <option value="TN">Tennessee</option>
        <option value="WI">Wisconsin</option>
      </optgroup>
      <optgroup label="Eastern Time Zone">
        <option value="CT">Connecticut</option>
        <option value="DE">Delaware</option>
        <option value="FL">Florida</option>
        <option value="GA">Georgia</option>
        <option value="IN">Indiana</option>
        <option value="ME">Maine</option>
        <option value="MD">Maryland</option>
        <option value="MA">Massachusetts</option>
        <option value="MI">Michigan</option>
        <option value="NH">New Hampshire</option>
        <option value="NJ">New Jersey</option>
        <option value="NY">New York</option>
        <option value="NC">North Carolina</option>
        <option value="OH">Ohio</option>
        <option value="PA">Pennsylvania</option>
        <option value="RI">Rhode Island</option>
        <option value="SC">South Carolina</option>
        <option value="VT">Vermont</option>
        <option value="VA">Virginia</option>
        <option value="WV">West Virginia</option>
      </optgroup>
    </select>
    
    using destroy: 
    <select class="js-example-programmatic">
      <optgroup label="Alaskan/Hawaiian Time Zone">
        <option value="AK">Alaska</option>
        <option value="HI">Hawaii</option>
      </optgroup>
      <optgroup label="Pacific Time Zone">
        <option value="CA">California</option>
        <option value="NV">Nevada</option>
        <option value="OR">Oregon</option>
        <option value="WA">Washington</option>
      </optgroup>
      <optgroup label="Mountain Time Zone">
        <option value="AZ">Arizona</option>
        <option value="CO">Colorado</option>
        <option value="ID">Idaho</option>
        <option value="MT">Montana</option>
        <option value="NE">Nebraska</option>
        <option value="NM">New Mexico</option>
        <option value="ND">North Dakota</option>
        <option value="UT">Utah</option>
        <option value="WY">Wyoming</option>
      </optgroup>
      <optgroup label="Central Time Zone">
        <option value="AL">Alabama</option>
        <option value="AR">Arkansas</option>
        <option value="IL">Illinois</option>
        <option value="IA">Iowa</option>
        <option value="KS">Kansas</option>
        <option value="KY">Kentucky</option>
        <option value="LA">Louisiana</option>
        <option value="MN">Minnesota</option>
        <option value="MS">Mississippi</option>
        <option value="MO">Missouri</option>
        <option value="OK">Oklahoma</option>
        <option value="SD">South Dakota</option>
        <option value="TX">Texas</option>
        <option value="TN">Tennessee</option>
        <option value="WI">Wisconsin</option>
      </optgroup>
      <optgroup label="Eastern Time Zone">
        <option value="CT">Connecticut</option>
        <option value="DE">Delaware</option>
        <option value="FL">Florida</option>
        <option value="GA">Georgia</option>
        <option value="IN">Indiana</option>
        <option value="ME">Maine</option>
        <option value="MD">Maryland</option>
        <option value="MA">Massachusetts</option>
        <option value="MI">Michigan</option>
        <option value="NH">New Hampshire</option>
        <option value="NJ">New Jersey</option>
        <option value="NY">New York</option>
        <option value="NC">North Carolina</option>
        <option value="OH">Ohio</option>
        <option value="PA">Pennsylvania</option>
        <option value="RI">Rhode Island</option>
        <option value="SC">South Carolina</option>
        <option value="VT">Vermont</option>
        <option value="VA">Virginia</option>
        <option value="WV">West Virginia</option>
      </optgroup>
    </select>
    
    <button class="js-programmatic-set-val">set value</button>

    0 讨论(0)
  • 2020-11-30 00:39

    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');
    
    0 讨论(0)
  • 2020-11-30 00:39

    For Ajax, use $(".select2").val("").trigger("change"). That should solve the problem.

    0 讨论(0)
  • 2020-11-30 00:39

    HTML

    <select id="lang" >
       <option value="php">php</option>
       <option value="asp">asp</option>
       <option value="java">java</option>
    </select>
    

    JS

     $("#lang").select2().val('php').trigger('change.select2');
    

    source: https://select2.github.io/options.html

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