I am creating and populating a list with jQuery and want to add an li element dynamically.
I’ve tried the following but it didnt work for me. Instead the browser crashed. Can anyone help?
$(document).ready(function() {
$(".tophundredwatchlist").hide();
$(".addtophundredwatchlist").click(function() {
$.ajax({
type : "GET",
url : "/watchlisttophundred/",
success : function(data){
generateList(data);
}
});
$(this).next().toggle();
return false;
});
//this section draws the list
function generateList(data)
{
var raw_tag = "<ul id='listwatchlist' class='listwatchlist'>";
var add_new = "Add New"
var json_array = data.json_array;
for (var json_count = 0; json_count < json_array.length; json_count++)
{
var raw_string = "<li id='watchlistitem' class='watchlistitem'>" + json_array[json_count].watch_list_name + "</li>"
raw_tag = raw_tag + raw_string
}
raw_tag = raw_tag + "<div id='addnew' class='addnew'>" + add_new + "</div>"
raw_tag = raw_tag + "<div id='newtext' class='newtext'></div>"
raw_tag = raw_tag + "</ul>"
$(".listwatchlist").html(raw_tag)
}
//when i try to add the new li like this my browser crashes
$('.newwatchlisttext').live("keypress",function(event) {
if(event.which == '13'){
var watch_list_name = $(this).val();
/**********************************************************/
$.ajax({
type : "GET",
url : "/addwatchlistfromtophundredajaxhandler/",
data : "watch_list_name=" + watch_list_name,
success : function(msg){
//$("listwatchlist ul").append('<li>' + data.watch_list_name + '</li>');
}
});
/**********************************************************/
$(".addnew").show()
$(".newtext").hide()
}
});
Your selector is wrong. You should replace this line:
with:
Oh and also the nesting the
divin theulas the other answer points out.