views:

623

answers:

7

I have this <ul>

<ul id="select_opts" class="bullet-list" style="margin-left:15px;"></ul>

This javascript code which is meant to go throug a JSON object and add the options to the UL:

$.each(q.opts, function(i,o)
{                        
    var str='';
    str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
    str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
    $("#select_opts").append(str);

});

If I do console.log() I can see that the looping is working. If I do:

console.log($("#select_opts").html());

It shows the HTML being updated as expected. However in the browser window, it shows the UL as empty!

What am I doing wrong?

+5  A: 
$("select_opts").append(str);

should be

$("#select_opts").append(str);
Vincent Ramdhanie
That doesn't work either
Click Upvote
+3  A: 

you're referring to object by id so you missed #

$.each(q.opts, function(i,o)
{                        
    var str='';
    str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
    str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
    $("#select_opts").append(str);
   //  ^
}
Michal M
That doesn't work either
Click Upvote
if it doesn't try checking if the loop is actually executed?try putting alert('this works'); inside.
Michal M
A: 

I'd imagine input needs to be properly self-closed.

SilentGhost
only if it's xhtml, but even then, this shouldn't affect the javascript.
Michal M
+1  A: 

Is this a typo?:

$("select_opts").append(str);

Did you mean?:

$("#select_opts").append(str);

UPDATED:

Try this:

$.each(q.opts, function(i, o) {
    var li = $('<li>').attr('id', 'li_' + i);
    var in = $('<input>').attr('type', 'text').attr('id', 'opt_' + i).val(o.option);
    var aa = $('<a>').attr('href', 'javascript:delOpt(' + i + ');').text('Delete');
    li.append(in).append(aa)
    $("#select_opts").append(li);
});
eu-ge-ne
+1  A: 

I can't really see what's wrong, but try this instead, just to see if it works...

$(str).appendTo("#select_opts");

Both should work.

Jarrett Meyer
A: 

I found the bug, another part of the code was emptying the <ul> when i clicked a certain button.

Click Upvote
+1  A: 

The tag Input should be closed - if don't, when using not valid html in append() on Internet Explorer, the div is not put into DOM tree, so you cannot access it with jQuery later.

pbrodka
You mean the <input> tags?
Click Upvote
Yes - <input/> tag
pbrodka