Lara Lara - 1 year ago 66
Javascript Question

Adding dropdown values dynamically

I have a dropdown Markup like

<ul class="dropdown-menu">
<li><a href="#"></a></li>

From Server side I am getting values to be added as Comma separated like.

var dropdownMenuItems = "ADD,Substract,Multiply";

Now I want to add above values for which I have written like

for (var i = 0; i <= dropdownMenuItems.length; i++)
$('.dropdown-menu a').add(dropdownMenuItems[i]);

but I am getting error like
JavaScript runtime error: Syntax error, unrecognized expression: ,
in console.
Please help.

Answer Source

You need to split the string in to an array using split(). Then you need to loop through it and create the li and a elements and append() them to the ul. Try this:

var arr = "ADD,Substract,Multiply".split(',');
var html = ''
for (var i = 0; i < arr.length; i++) {
  html += '<li><a href="#">' + arr[i] + '</a></li>';
<script src=""></script>
<ul class="dropdown-menu"></ul>

Note that you should use < not <= in the for loop, and add() is used to add elements to an existing jQuery object, not create content in the DOM.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download