Create Dynamic Div With Unique Ids - Jquery
Solution 1:
You can just use an incrementing ID variable, like this:
var i = 1;
$("#addProduct").click(function() {
$("<div />", { "class":"wrapper", id:"product"+i })
.append($("<input />", { type: "text", id:"name"+i }))
.append($("<input />", { type: "text", id:"property"+i }))
.appendTo("#someContainer");
i++;
});
You can give it a try here, this is a very general answer, but you get the idea, just increment the variable after adding your items each time.
Solution 2:
Ok. This is a really old post but I thought it might help if you're having a similar issue. I came across the .uniqueId() in jQuery (see here).
It checks whether the element already has an id or not and if it doesn't, it assigns a unique id to it. The drawback is that you cannot have a 'custom id name' to it (such as product_1, product_2, etc). The id assigned is something like ui-id-1, ui-id-2, etc.
To assign a unique id, you can so something like this -
$("<div class='someDivConntet'></div>").insertAfter($(this)).uniqueId();
Just make sure you don't have an id set on the element already.
Solution 3:
$(function(){
var pcount = icount = 0;
$('<div/>', {
id: 'product' + pcount++
}).append($('<input/>', {
id: 'input' + icount++
})).append($('<input/>', {
id: 'input' + icount++
})).appendTo(document.body);
});
Solution 4:
Generally you don't need to use IDs in this way.
Once you've created the new element using Javascript, you already have an object which you can pass around, into functions etc. You certainly don't need to pass the ID around just so that you can pass it into document.getElementByID()
Solution 5:
I'm using this one I've made
$.fn.uniqueId = function(idlength){
var charstoformid = '_0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (! idlength) idlength = 10;
var getId = function() {
var uniqid = '';
for (var i = 0; i < idlength; i++) {
uniqid += charstoformid[Math.floor(Math.random() * charstoformid.length)];
}
return uniqid;
}
return $(this).each(function(){
var id = getId()
while ( $("#"+id).length ) {
id = getId();
}
$(this).attr("id", id);
});
}
It has function to generate random chars chain, then it make sure that generated one is unique (that has 0,000001% of possibility - but it's possible) and then change id.
Post a Comment for "Create Dynamic Div With Unique Ids - Jquery"