0

I want to add <option> tag using for loop inside jquery .after() function. I have the following code:

$("#myid").after("<!--more tags here-->"+
                  "<select class='form-control' name='dropdownmenu'>"+
                  "for (i=0; i < 4 ; i++){"+
                  "<option>i</option>}"+
                  "</select>"+
                  "<!--more tags here-->")

But that doesn't work, all I get is 1 <option> tag with the letter i inside

3 Answers3

1

you can not loop in js like that. you can something like following. You can create your select block first and then append it. code not tested, hopefully you get the idea.

var test = "<select class='form-control' name='dropdownmenu'>";

for (i=0; i < 4 ; i++){
    test += "<option>"+i+"</option>}";                  
}
test += "</select>";

$("#myid").after(test);  // note: use . for class or # for id

you can still add more tags this way:

$("#myid").after("<span>start</span>"+test+"<span>end</span>");  
tech2017
  • 1,806
  • 1
  • 13
  • 15
  • The problem is that in the actual code there are more tags added before and after the –  Jun 09 '17 at 19:46
  • Thank you, and last thing, I just noticed that for making the code here simpler, I changed an important piece, and your code works for the #id, but my actual code is using .class:last like that: (.myclass : last).after() What fix I can apply for that? I can't make it work with this little change –  Jun 09 '17 at 20:01
  • are you missing quotes? (".myclass : last"). – tech2017 Jun 12 '17 at 12:40
0

@techLove answer is valid.

But if you absolutely must, you can use .map() for that:

$("#myid").after("<!--more tags here-->"+
                  "<select class='form-control' name='dropdownmenu'>"+
                  [0, 1, 2, 3].map(i => "<option>"+i+"</option>") +
                  "</select>"+
                  "<!--more tags here-->")
Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40
0

I know that this question already has an answer, but, thanks to it, i've learned something new and i want to share this knowledge.

This way to do it, is, IMHO, cleaner and more elegant.

var options = [0, 1, 2, 3];

$(function() {
  var $select = $('<select>', {
    class: 'form-control',
    name: 'dropdownmenu',
    html: options.map(function(option) {
      return $('<option>', {
        value: option,
        text: option
      })
    })
  }).appendTo('.wrapper');
  
  //if you really want to use after, remove "appendTo" and use this
  //$('.wrapper').after($select);
});
.wrapper {
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper"></div>
<div class="wrapper"></div>
<div class="wrapper"></div>
<div class="wrapper"></div>
<div class="wrapper"></div>
<div class="wrapper"></div>
apires
  • 917
  • 1
  • 9
  • 18