Kim
Kim

Reputation: 1156

Unique element ID

I am having an issue with unique element id's?

What am I doing wrong here?

http://jsfiddle.net/KRRES/

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

Answers (3)

Dharmesh Patel
Dharmesh Patel

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

T.J. Crowder
T.J. Crowder

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

Kevin Bowersox
Kevin Bowersox

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

Related Questions