2

I'm trying to create a dynamic dropdown using jquery

   var rooms = $("<select />");

   $(res.data).each(function () {
         var option = $("<option />");
         option.html(this.name);
         option.val(this.id);
         rooms.append(option);
   });
 

dropdown is created when i directly append it to append_parent_div

$('#append_parent_div').append(rooms);

but when i append it with several div's

  $('#append_parent_div').append('<div class="col-lg-6 col-md-12 col-12"> <div class="form-group">'+rooms+'</div></div>');

then [object Object] is getting appended in my html.

1 Answer 1

1

do not use +, but ,:

example:

$('#append_parent_div').append('<div class="col-lg-6 col-md-12 col-12"> <div class="form-group">', rooms, '</div></div>');

Like documentantion said: https://api.jquery.com/append/

You were concatenating strings with an object

Working example:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div id="append_parent_div">
    </div>
    <script>
    var rooms = $("<select />");
    var res =  {};
    res.data = [{name:"name number 1", id:1},{name:"name number 2", id:2}]

    $(res.data).each(function () {
            var option = $("<option />");
            option.html(this.name);
            option.val(this.id);
            rooms.append(option);
    });

  $('#append_parent_div').append('<div class="col-lg-6 col-md-12 col-12"> <div class="form-group">', rooms, '</div></div>');
    </script>
</body>
</html>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer but there is one issue dropdown is created outside the form group i want to create it within form group
oh sorry, didnt understood that... so you can use $('#append_parent_div').append('<div class="col-lg-6 col-md-12 col-12"><div class="form-group">' + rooms.get(0).outerHTML + '</div></div>');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.