Lara
Lara

Reputation: 3021

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.

Upvotes: 2

Views: 63

Answers (3)

Durgesh Ahire
Durgesh Ahire

Reputation: 117

try this one. it works

var dropdownMenuItems = "ADD,Substract,Multiply";
var list  = dropdownMenuItems.split(',');
$('.dropdown-menu').html('');
for (var i = 0; i <= list.length; i++)
 {
    $('.dropdown-menu').append('<li><a href="#">' + list[i] + '</a></li>');
 }

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

Try like this:

var result = 'ADD,Substract,Multiply';

$('.myClass').html($.map(result.split(','), function(item) 
{
  return $('<option></option>').val(item).html(item)[0].outerHTML
}).join(''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select class="myClass">
</select>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 2

Related Questions