2

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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

1 Comment

Nice solution - but you're creating option elements in a select, whereas the OP is clearly creating li in a ul. Also note that map() is unsupported in <IE9 if you need legacy browser support
1

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>');
 }

3 Comments

Are you sure this works? <= in the loop will mean it iterates one time too many, and add() doesn't do what you are expecting it to.
Missed the <= ;)
Now its woking fine :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.