jquery - Assigning ID's to dynamic elements which can be added or removed -


i have web interface users can click on 'add item...' button , div appended:

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

as user may create number of these items, must assign unique id each one, have tried following:

var idnumber = $('.item').length + 1;  $('#item-list').append('<div id="' + idnumber + '" class="item">new item</div>'); 

this works fine part except 1 important thing: user can delete 1 or more of these items well. introduces possibility of duplicate ids.

for example:

i have 5 items ids 1,2,3,4 , 5. delete item 3, when create next item counts 4 items , gives new item id count + 1 5 (duplicate).

how go resolving issue? usual procedure in situation?

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 added 'd' in there, don't think number ids compliant.


Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -