Reputation: 1876
I have to add elements to an HTML page dynamically using jquery and set some event handler for that. I am using this code :
$('.orderedList').append("<li class='il l' + i>" + $('.nam').val() + "</li>");
I want to assign two classes to the list item, one will set CSS attributes and the other class (l5
, if i = 5
) will control the click listener for that list item.
My problem is that the second class ('l' + i
) is not set. Maybe there's some error in my code. Any suggestions ?
Upvotes: 1
Views: 51
Reputation: 337646
Your string is incorrectly quoted, so the concatenation is not happening as you require. Try this:
$('.orderedList').append('<li class="il l' + i + '">' + $('.nam').val() + '</li>');
I would suggest you use a text editor which has syntax highlighting to write your JS code. It makes it trivial to spot and fix problems like this.
You could also achieve the above by creating the element as an object, avoiding execessive string concatenation.
$('<li />', {
class: 'il l' + i,
text: $('.nam').val()
}).appendTo('.orderedList');
Upvotes: 3
Reputation: 48425
Assuming i
is a javascrpt variable, you need to change it to this:
$('.orderedList').append("<li class='il l" + i + "'>" + $('.nam').val() + "</li>");
Notice the way that the html string is being constructed
Upvotes: 3