Lara Lara - 3 months ago 6
Javascript Question

Adding dropdown values dynamically

I have a dropdown Markup like

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


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

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>';
}
$('.dropdown-menu').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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.

Comments