0

I have a web interface where users can click on an 'add item...' button and a div is appended:

$('#item-list').append('<div id="newID" class="item">New item</div>');

As a user may create any number of these items, I must assign a unique id to each one, I have tried the following:

var idNumber = $('.item').length + 1;

$('#item-list').append('<div id="' + idNumber + '" class="item">New item</div>');

This works fine for the most part except for one important thing: The user can delete one or more of these items as well. This introduces the possibility of duplicate ids.

For example:

I have 5 items with ids 1,2,3,4 and 5. I delete item 3, when I create my next item it counts 4 items and gives the new item id count + 1 which is 5 (duplicate).

How would I go about resolving the issue? What is the usual procedure in this situation?

PaulG
  • 6,920
  • 12
  • 54
  • 98
  • 2
    get the last id and add 1 – depperm Jun 10 '15 at 14:35
  • Right, I thought of that. Is it common practice? There probably isn't any other way around it. – PaulG Jun 10 '15 at 14:36
  • That or make the id unique to the new div contents, what does the div contain? Are they unique besides id? – depperm Jun 10 '15 at 14:37
  • @depperm All of these new divs start out with the same shell but are editable, so off the bat there's nothing unique about them. – PaulG Jun 10 '15 at 14:38
  • 2
    Just use a counter, or use a generated random number. – Ted Jun 10 '15 at 14:38
  • Don't use incremental `id` - it ends up being a maintenance nightmare. Use common classes and traverse the DOM to find related elements under the required events instead. – Rory McCrossan Jun 10 '15 at 14:41

3 Answers3

1

Something like this:

var count = 0;

$('addItemButtonSelector').click(function(e){
    $('#item-list').append('<div id="newID'+count+'" class="item">New item</div>');
    count++;
});

That way it'll always be unique...the variable count is incremented +1 every time an element is added.

Ted
  • 14,757
  • 2
  • 41
  • 58
1

If what you are looking to do is have uniquely generated IDs, then I suggest using a GUID. Support for GUID generation is not native in JS, but this post provides the following function for their creation:

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

You can customize the return statement to use your desired GUID format. You would basically have something like the following though:

$('#item-list').append('<div id="' + guid() + '" class="item">New item</div>');

I grant you that the performance of GUID creation is less than that of incrementing and concatenating, but GUIDs give you highly "unique" (extremely unlikely to get two of the same) IDs and generate them without having to create loops. Support for GUIDS is usually included in back-end languages, like PHP and C#, as well as database scripting languages, like SQL and MySQL. As such, they can be a pretty powerful tool, depending on the task at hand.

The below is a little demo:

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}


$(document).ready(function() {
  var $itemList = $('#item-list');
  var $itemIdList = $('#item-id-list');

  $("#btnAddElement").on("click", function() {
    $itemList.append('<div id="' + guid() + '" class="item">New item</div>');
    $itemIdList.append('<li>' + $itemList.children().last().attr('id') + '</li>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
  <div id="item-list"></div>
  <ol id="item-id-list"></ol>
</div>
<button type="button" id="btnAddElement">Add an element</button>
Community
  • 1
  • 1
Zachary Kniebel
  • 4,686
  • 3
  • 29
  • 53
1

Try:

var lastId = 0;
$('.item').each(function (el) {
    var id = parseInt($(this).attr('id').splice(1), 10);
    if (id > lastId) {
        lastId = id;
    }
});
lastId += 1;
$('#item-list').append('<div id="d' + lastId + '" class="item">New item</div>');

Notice I added an extra 'd' in there, I don't think number ids are compliant.

PaulG
  • 6,920
  • 12
  • 54
  • 98
beautifulcoder
  • 10,832
  • 3
  • 19
  • 29
  • I think in HTML5 numbers _are_ compliant, but still, in my opinion, it's bad form ;) – Ted Jun 10 '15 at 14:43