简体   繁体   中英

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
 //}

});

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 (eg, 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM