select2 - how preselecting multiple options that receive data from an AJAX remote source












0














I have a modal that has two 'behaviors', one to create new record and another to edit existing record, depending on which button is clicked (new / edit).



When you click edit, the record data (users table) is loaded 'along' with the child records (permissions table).



During modal loading, the select2 is initialized:



let $select2user    = $(".select2user");

$select2user.select2({
ajax: {
url: 'getUsersWithPermissions.php',
type: "GET",
dataType: 'json',
data: function (params) {
return {
search: params.term,
page: params.page || 1
};
},
processResults: function (data) {
data.page = data.page || 1;
return {
results: data.items.map(function (item) {
return {
id: item.id,
text: item.name
};
})
}
},
cache: true,
delay: 250
},
multiple: true
});


Everything works fine, except when I click edit a record.



The inputs form (modal) are filled in correctly with the registration data, however, I cannot pre-select multiple options from child records (permissions table).



I tried to use 'append', but it ends up generating duplicate options.



$.each( value, function( permissions, permission ) {
console.log(permission['name']); // ok
let newOption = new Option(permission['name'], permission['id'], false, true);
$select2user.append(newOption);
});
$select2user.trigger('change');









share|improve this question



























    0














    I have a modal that has two 'behaviors', one to create new record and another to edit existing record, depending on which button is clicked (new / edit).



    When you click edit, the record data (users table) is loaded 'along' with the child records (permissions table).



    During modal loading, the select2 is initialized:



    let $select2user    = $(".select2user");

    $select2user.select2({
    ajax: {
    url: 'getUsersWithPermissions.php',
    type: "GET",
    dataType: 'json',
    data: function (params) {
    return {
    search: params.term,
    page: params.page || 1
    };
    },
    processResults: function (data) {
    data.page = data.page || 1;
    return {
    results: data.items.map(function (item) {
    return {
    id: item.id,
    text: item.name
    };
    })
    }
    },
    cache: true,
    delay: 250
    },
    multiple: true
    });


    Everything works fine, except when I click edit a record.



    The inputs form (modal) are filled in correctly with the registration data, however, I cannot pre-select multiple options from child records (permissions table).



    I tried to use 'append', but it ends up generating duplicate options.



    $.each( value, function( permissions, permission ) {
    console.log(permission['name']); // ok
    let newOption = new Option(permission['name'], permission['id'], false, true);
    $select2user.append(newOption);
    });
    $select2user.trigger('change');









    share|improve this question

























      0












      0








      0







      I have a modal that has two 'behaviors', one to create new record and another to edit existing record, depending on which button is clicked (new / edit).



      When you click edit, the record data (users table) is loaded 'along' with the child records (permissions table).



      During modal loading, the select2 is initialized:



      let $select2user    = $(".select2user");

      $select2user.select2({
      ajax: {
      url: 'getUsersWithPermissions.php',
      type: "GET",
      dataType: 'json',
      data: function (params) {
      return {
      search: params.term,
      page: params.page || 1
      };
      },
      processResults: function (data) {
      data.page = data.page || 1;
      return {
      results: data.items.map(function (item) {
      return {
      id: item.id,
      text: item.name
      };
      })
      }
      },
      cache: true,
      delay: 250
      },
      multiple: true
      });


      Everything works fine, except when I click edit a record.



      The inputs form (modal) are filled in correctly with the registration data, however, I cannot pre-select multiple options from child records (permissions table).



      I tried to use 'append', but it ends up generating duplicate options.



      $.each( value, function( permissions, permission ) {
      console.log(permission['name']); // ok
      let newOption = new Option(permission['name'], permission['id'], false, true);
      $select2user.append(newOption);
      });
      $select2user.trigger('change');









      share|improve this question













      I have a modal that has two 'behaviors', one to create new record and another to edit existing record, depending on which button is clicked (new / edit).



      When you click edit, the record data (users table) is loaded 'along' with the child records (permissions table).



      During modal loading, the select2 is initialized:



      let $select2user    = $(".select2user");

      $select2user.select2({
      ajax: {
      url: 'getUsersWithPermissions.php',
      type: "GET",
      dataType: 'json',
      data: function (params) {
      return {
      search: params.term,
      page: params.page || 1
      };
      },
      processResults: function (data) {
      data.page = data.page || 1;
      return {
      results: data.items.map(function (item) {
      return {
      id: item.id,
      text: item.name
      };
      })
      }
      },
      cache: true,
      delay: 250
      },
      multiple: true
      });


      Everything works fine, except when I click edit a record.



      The inputs form (modal) are filled in correctly with the registration data, however, I cannot pre-select multiple options from child records (permissions table).



      I tried to use 'append', but it ends up generating duplicate options.



      $.each( value, function( permissions, permission ) {
      console.log(permission['name']); // ok
      let newOption = new Option(permission['name'], permission['id'], false, true);
      $select2user.append(newOption);
      });
      $select2user.trigger('change');






      jquery ajax jquery-select2






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 at 1:12









      Magno Alberto

      5310




      5310
























          1 Answer
          1






          active

          oldest

          votes


















          0

















          $(document).ready(function() { 
          $("#selectlist").select2();

          var _selectedValues = ;
          _selectedValues.push('1');
          _selectedValues.push('5');
          _selectedValues.push('8');
          $("#selectlist").select2().val(_selectedValues).trigger("change");

          });

          <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
          <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.5/js/select2.min.js"></script>
          <select id="selectlist" class="form-control" name="selectList" multiple="multiple" style="width:200px">
          <option value="1">One</option>
          <option value="2">Two</option>
          <option value="3">Three</option>
          <option value="4">Four</option>
          <option value="5">Five</option>
          <option value="6">Six</option>
          <option value="7">Seven</option>
          <option value="8">Eight</option>
          <option value="9">Nine</option>
          <option value="10">Ten</option>
          </select>





          You can try like this, to set the values in select2.



          var _selectedValues = ;
          _selectedValues.push('1');
          _selectedValues.push('2');
          _selectedValues.push('3');
          $("#selectlist").select2().val(_selectedValues).trigger("change");





          share|improve this answer























          • Thanks for the collaboration, however, your suggestion works for 'static' options, but unfortunately, it does not work for 'dynamically' loaded (remote source ajax) options.
            – Magno Alberto
            Nov 12 at 10:44






          • 1




            As you mentioned, you are getting duplicate options (by append), instead of append, add the id to array and execute this code in ajax success block,
            – Aquib Iqbal
            Nov 12 at 11:08











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254841%2fselect2-how-preselecting-multiple-options-that-receive-data-from-an-ajax-remot%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0

















          $(document).ready(function() { 
          $("#selectlist").select2();

          var _selectedValues = ;
          _selectedValues.push('1');
          _selectedValues.push('5');
          _selectedValues.push('8');
          $("#selectlist").select2().val(_selectedValues).trigger("change");

          });

          <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
          <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.5/js/select2.min.js"></script>
          <select id="selectlist" class="form-control" name="selectList" multiple="multiple" style="width:200px">
          <option value="1">One</option>
          <option value="2">Two</option>
          <option value="3">Three</option>
          <option value="4">Four</option>
          <option value="5">Five</option>
          <option value="6">Six</option>
          <option value="7">Seven</option>
          <option value="8">Eight</option>
          <option value="9">Nine</option>
          <option value="10">Ten</option>
          </select>





          You can try like this, to set the values in select2.



          var _selectedValues = ;
          _selectedValues.push('1');
          _selectedValues.push('2');
          _selectedValues.push('3');
          $("#selectlist").select2().val(_selectedValues).trigger("change");





          share|improve this answer























          • Thanks for the collaboration, however, your suggestion works for 'static' options, but unfortunately, it does not work for 'dynamically' loaded (remote source ajax) options.
            – Magno Alberto
            Nov 12 at 10:44






          • 1




            As you mentioned, you are getting duplicate options (by append), instead of append, add the id to array and execute this code in ajax success block,
            – Aquib Iqbal
            Nov 12 at 11:08
















          0

















          $(document).ready(function() { 
          $("#selectlist").select2();

          var _selectedValues = ;
          _selectedValues.push('1');
          _selectedValues.push('5');
          _selectedValues.push('8');
          $("#selectlist").select2().val(_selectedValues).trigger("change");

          });

          <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
          <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.5/js/select2.min.js"></script>
          <select id="selectlist" class="form-control" name="selectList" multiple="multiple" style="width:200px">
          <option value="1">One</option>
          <option value="2">Two</option>
          <option value="3">Three</option>
          <option value="4">Four</option>
          <option value="5">Five</option>
          <option value="6">Six</option>
          <option value="7">Seven</option>
          <option value="8">Eight</option>
          <option value="9">Nine</option>
          <option value="10">Ten</option>
          </select>





          You can try like this, to set the values in select2.



          var _selectedValues = ;
          _selectedValues.push('1');
          _selectedValues.push('2');
          _selectedValues.push('3');
          $("#selectlist").select2().val(_selectedValues).trigger("change");





          share|improve this answer























          • Thanks for the collaboration, however, your suggestion works for 'static' options, but unfortunately, it does not work for 'dynamically' loaded (remote source ajax) options.
            – Magno Alberto
            Nov 12 at 10:44






          • 1




            As you mentioned, you are getting duplicate options (by append), instead of append, add the id to array and execute this code in ajax success block,
            – Aquib Iqbal
            Nov 12 at 11:08














          0












          0








          0









          $(document).ready(function() { 
          $("#selectlist").select2();

          var _selectedValues = ;
          _selectedValues.push('1');
          _selectedValues.push('5');
          _selectedValues.push('8');
          $("#selectlist").select2().val(_selectedValues).trigger("change");

          });

          <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
          <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.5/js/select2.min.js"></script>
          <select id="selectlist" class="form-control" name="selectList" multiple="multiple" style="width:200px">
          <option value="1">One</option>
          <option value="2">Two</option>
          <option value="3">Three</option>
          <option value="4">Four</option>
          <option value="5">Five</option>
          <option value="6">Six</option>
          <option value="7">Seven</option>
          <option value="8">Eight</option>
          <option value="9">Nine</option>
          <option value="10">Ten</option>
          </select>





          You can try like this, to set the values in select2.



          var _selectedValues = ;
          _selectedValues.push('1');
          _selectedValues.push('2');
          _selectedValues.push('3');
          $("#selectlist").select2().val(_selectedValues).trigger("change");





          share|improve this answer

















          $(document).ready(function() { 
          $("#selectlist").select2();

          var _selectedValues = ;
          _selectedValues.push('1');
          _selectedValues.push('5');
          _selectedValues.push('8');
          $("#selectlist").select2().val(_selectedValues).trigger("change");

          });

          <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
          <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.5/js/select2.min.js"></script>
          <select id="selectlist" class="form-control" name="selectList" multiple="multiple" style="width:200px">
          <option value="1">One</option>
          <option value="2">Two</option>
          <option value="3">Three</option>
          <option value="4">Four</option>
          <option value="5">Five</option>
          <option value="6">Six</option>
          <option value="7">Seven</option>
          <option value="8">Eight</option>
          <option value="9">Nine</option>
          <option value="10">Ten</option>
          </select>





          You can try like this, to set the values in select2.



          var _selectedValues = ;
          _selectedValues.push('1');
          _selectedValues.push('2');
          _selectedValues.push('3');
          $("#selectlist").select2().val(_selectedValues).trigger("change");





          $(document).ready(function() { 
          $("#selectlist").select2();

          var _selectedValues = ;
          _selectedValues.push('1');
          _selectedValues.push('5');
          _selectedValues.push('8');
          $("#selectlist").select2().val(_selectedValues).trigger("change");

          });

          <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
          <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.5/js/select2.min.js"></script>
          <select id="selectlist" class="form-control" name="selectList" multiple="multiple" style="width:200px">
          <option value="1">One</option>
          <option value="2">Two</option>
          <option value="3">Three</option>
          <option value="4">Four</option>
          <option value="5">Five</option>
          <option value="6">Six</option>
          <option value="7">Seven</option>
          <option value="8">Eight</option>
          <option value="9">Nine</option>
          <option value="10">Ten</option>
          </select>





          $(document).ready(function() { 
          $("#selectlist").select2();

          var _selectedValues = ;
          _selectedValues.push('1');
          _selectedValues.push('5');
          _selectedValues.push('8');
          $("#selectlist").select2().val(_selectedValues).trigger("change");

          });

          <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
          <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.5/js/select2.min.js"></script>
          <select id="selectlist" class="form-control" name="selectList" multiple="multiple" style="width:200px">
          <option value="1">One</option>
          <option value="2">Two</option>
          <option value="3">Three</option>
          <option value="4">Four</option>
          <option value="5">Five</option>
          <option value="6">Six</option>
          <option value="7">Seven</option>
          <option value="8">Eight</option>
          <option value="9">Nine</option>
          <option value="10">Ten</option>
          </select>






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 12 at 6:41

























          answered Nov 12 at 6:26









          Aquib Iqbal

          21417




          21417












          • Thanks for the collaboration, however, your suggestion works for 'static' options, but unfortunately, it does not work for 'dynamically' loaded (remote source ajax) options.
            – Magno Alberto
            Nov 12 at 10:44






          • 1




            As you mentioned, you are getting duplicate options (by append), instead of append, add the id to array and execute this code in ajax success block,
            – Aquib Iqbal
            Nov 12 at 11:08


















          • Thanks for the collaboration, however, your suggestion works for 'static' options, but unfortunately, it does not work for 'dynamically' loaded (remote source ajax) options.
            – Magno Alberto
            Nov 12 at 10:44






          • 1




            As you mentioned, you are getting duplicate options (by append), instead of append, add the id to array and execute this code in ajax success block,
            – Aquib Iqbal
            Nov 12 at 11:08
















          Thanks for the collaboration, however, your suggestion works for 'static' options, but unfortunately, it does not work for 'dynamically' loaded (remote source ajax) options.
          – Magno Alberto
          Nov 12 at 10:44




          Thanks for the collaboration, however, your suggestion works for 'static' options, but unfortunately, it does not work for 'dynamically' loaded (remote source ajax) options.
          – Magno Alberto
          Nov 12 at 10:44




          1




          1




          As you mentioned, you are getting duplicate options (by append), instead of append, add the id to array and execute this code in ajax success block,
          – Aquib Iqbal
          Nov 12 at 11:08




          As you mentioned, you are getting duplicate options (by append), instead of append, add the id to array and execute this code in ajax success block,
          – Aquib Iqbal
          Nov 12 at 11:08


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254841%2fselect2-how-preselecting-multiple-options-that-receive-data-from-an-ajax-remot%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          Xamarin.form Move up view when keyboard appear

          Post-Redirect-Get with Spring WebFlux and Thymeleaf

          Anylogic : not able to use stopDelay()