Ad

For Each Option From Select2 Multiple, Append Option Value Text Into Div Using Jquery

With a I want to press a button, add the selected item (s) to a div #list

<select class="select2" multiple="multiple" name="string_items[]" id="string_items">
  <option>value i want to append</option>
</select>

move on from this:   to this (assuming that each item is a template using .append ("<div class =" item ">" + option text + "</div>") + the text that contains each )

<div id="list">
    <div class="item">appended value</div>
</div>

I am not an expert in JS but I have the idea of what I want. My JS code:

$("#post-button").click(function(e){
  var items_list = $('#string_items').val(); //combo box / <select id="string_items">

  //for each item {
    //var item_tpl = '<div class="item">'+ <OPTION> TEXT </OPTION> +'</div>';   //My simple but powerful template for this example
    //$("#list").append(item_tpl); //adding to #list div
 //}

});
Ad

Answer

You can try with for...of loop:

The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, Array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

$("#post-button").click(function(e){
  var items_list = $('#string_items').val();
  for (item of items_list){
    var item_tpl = '<div class="item"><OPTION> '+item+' </OPTION></div>';
    $("#list").append(item_tpl);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="select2" multiple="multiple" name="string_items[]" id="string_items">
<option>Value 1 to append</option>
<option>Value 2 to append</option>
</select>
<button type="button" id="post-button">Post</button>
<div id="list">
    <div class="item">appended value</div>
</div>

Ad
source: stackoverflow.com
Ad