Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic dropdown using jquery

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  $('#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.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading