Mike Muller
Mike Muller

Reputation: 2297

Taking a comma separated list and creating a unordered list

I've got a simple list which is generated by a checkbox list. The generated code is simply this

white,blue,red,black

I need to use jquery to wrap each of these elements in a < li > tag. How do you go through the list and use the comma as a separator? I also will need to delete the comma. Sometime there will be 1 item, sometimes 3, etc.

Thanks in advance!

Upvotes: 3

Views: 3662

Answers (4)

Ben
Ben

Reputation: 16553

<script type="text/javascript">
    var mystring = 'white,blue,red,black';
    mystring = '<ul><li>' + mystring.replace(/,/gi,'</li><li>') + '</li></ul>';
    document.write(mystring);
</script>

Outputs:

<ul>
<li>white</li>
<li>blue</li>
<li>red</li>
<li>black</li>
</ul>

This doesn't use jquery at all :)

Upvotes: 10

Anurag
Anurag

Reputation: 141879

lol, 1 character shorter than omfgroflmao :D and no jquery goodiness

mystring = '<ul>' + mystring.replace(/(\w+),?/g, '<li>$1</li>') + '</ul>';

with jquery goodiness 1 more character shortened.. haha

myobject = $('<ul>').append(mystring.replace(/(\w+),?/g, '<li>$1</li>'));

Upvotes: 1

wombleton
wombleton

Reputation: 8376

var el = $('#elementSelector');
var values = el.html().split(',');
el.html('<ul>' + $.map(values, function(v) { 
  return '<li>' + v + '</li>';
}).join('') + '</ul>');

Upvotes: 4

Sunny
Sunny

Reputation: 6346

var final_string = "<ul><li>" + myString.replace(/,/gi, '</li><li>') + "</li></ul>";

Upvotes: 0

Related Questions