Home > Blockchain >  Dynamic dropdown using jquery
Dynamic dropdown using jquery

Time:03-25

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 > <div >' rooms '</div></div>');

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

CodePudding user response:

do not use , but ,:

example:

$('#append_parent_div').append('<div > <div >', 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 > <div >', rooms, '</div></div>');
    </script>
</body>
</html>

  • Related