views:

22

answers:

2

I'm trying to create an unordered list dynamically and then turn it into jQuery UI tabs...

I think I'm having problem with syntax here, I managed to create the list and turn it into the widget, but those tabs don't look right, they have the outline of the widget but the content doesn't have actual tabs, so my guess is it only 'kind of worked'

$("#doc3").append("<ul>");

$("#doc3").append("<li><a href='#thisGame'>asass<a></li>");
$("#doc3").append("<li><a href='#thisGame2'>asass<a></li>");

$("#doc3").append("</ul>");

$("#doc3").append("<div id='thisGame'>sajaskj askj asjkasjk </div>");
$("#doc3").append("<div id='thisGame2'>sajaskj askj asjkasjk </div>");

$('#doc3').tabs();

is this the way to do it? (for now its just the test, eventually i want to use for loop to create the list and pull data from an array)

A: 

First, we need to close those anchors (</a>). The problem is that you add HTML and the browser looks at it and thinks "hey, he didn't close the tag... let's do it". So, when you appended the first UL ($("#doc3").append("<ul>");), it actually added <ul></ul>. To avoid this, just append self-contained chunks. E.g.

$("#doc3").append("<ul><li><a href='#thisGame'>asass</a></li><li><a href='#thisGame2'>asass</a></li></ul>");

That way, all the open tags has their corresponding ending tags and the tabs will appear.

Edit: Alternative version based on Kumu's comment.

$("#doc3").append("<ul></ul>");

var ULElement=$("#doc3 ul")

ULElement.append("<li><a href='#thisGame'>asass</a></li>");
ULElement.append("<li><a href='#thisGame2'>asass</a></li>");

$("#doc3").append("<div id='thisGame'>sajaskj askj asjkasjk </div>");
$("#doc3").append("<div id='thisGame2'>sajaskj askj asjkasjk </div>");

$('#doc3').tabs();
Gert G
You can also just remove the $("#doc3").append("</ul>");and when appending the "<li>" tags use the $("#doc3 ul") selector
Kumu
@Kumu - That will work. Good thinking. :)
Gert G
A: 

Gerts solution will work however putting it all in one long string will become a maintenance nightmare

For performance reasons it is preferred to build the markup in a string/array then append to the dom once rather than creating multiple jquery objects and invoking multiple dom appends.

You could do something like the following:

var builder = "<ul>";

for ( var i = 0; i < 5; i++ ){

    builder += "<li><a href='#thisGame"
    builder += i;
    builder += "'>asass<a></li>");

}

//build divs
builder += "<div />";

//close ul
builder += "</ul>";

//set markup of container
$("#doc3").html(builder);

//initialize tabs
$('#doc3').tabs();
redsquare