user7778602
user7778602

Reputation:

add for loop inside jquery .after() function

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

Upvotes: 0

Views: 162

Answers (3)

apires
apires

Reputation: 927

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>

Upvotes: 0

Alexey Soshin
Alexey Soshin

Reputation: 17721

@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-->")

Upvotes: 0

tech2017
tech2017

Reputation: 1806

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>");  

Upvotes: 1

Related Questions