Reputation: 1156
I am having an issue with unique element id's?
What am I doing wrong here?
HTML:
<div id='gmapItemHolder'></div>
<button id='btnCreateMarker'>Add</button>
Jquery:
$("#btnCreateMarker").click(function () {
i = 1;
var gmapItemsHolder = "gmapItems" + i++;
$('<ul>' + '</ul>')
.attr({id: gmapItemsHolder, class: 'gmapUlHolder row-fluid'}).prependTo('#gmapItemHolder')
});
UPDATE:
What happening is that all the newly created ul's get the ID 1
Upvotes: 1
Views: 75
Reputation: 1891
Try This:
var i =jQuery("#gmapItemHolder").children().length + 1;
var gmapItemsHolder = "gmapItems" + i;
Instead Of:
i = 1;
var gmapItemsHolder = "gmapItems" + i++;
Upvotes: 0
Reputation: 1074258
As Kevin said, the issue is that i
is used and thrown away each time.
But don't create a global variable as he suggests. Instead, wrap the code in a scoping function and define it there:
(function() {
var i = 1;
$("#btnCreateMarker").click(function () {
var gmapItemsHolder = "gmapItems" + i++;
$('<ul>'
+ '</ul>'
).attr({id: gmapItemsHolder, class: 'gmapUlHolder row-fluid'}).prependTo('#gmapItemHolder')
});
})();
That way, i
is shared by all calls to the click
event handler, but it is not a global variable.
Upvotes: 1
Reputation: 94459
The scope of i
is local so it does not retain state between clicks. Increase the scope of i
so that it is retained between events.
var i = 1;
$("#btnCreateMarker").click(function () {
var gmapItemsHolder = "gmapItems" + i++;
$('<ul>'
+ '</ul>'
).attr({id: gmapItemsHolder, class: 'gmapUlHolder row-fluid'}).prependTo('#gmapItemHolder')
});
Upvotes: 2