12

Let me know if I'm not explaining this well enough as I'm confusing myself just thinking about it.

I was to be able to click on a button that says "add product" and have it create a unique div each time. For example, the first div would have the id #product1, then #product2 etc.

The really tricky part is to have two input fields in the div, both regular text inputs. These also need to have unique IDs so I can use what is placed in them.

Let me know if you have any solutions. Thanks, Carson

Carson
  • 4,541
  • 9
  • 39
  • 45
  • What are you using these dynamic IDs for? – Gareth Aug 05 '10 at 15:25
  • Each div will have unique text input fields in them, which will then be used to output information such as titles, product and contact info to a PDF. I guess the ID doesn't really matter, but I can use the same process to generate unique names. – Carson Aug 06 '10 at 15:19

6 Answers6

21

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.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • PS I'm obviously new here so how do you make code look like code haha – Carson Aug 05 '10 at 16:01
  • Alright this is working, kind of. I can't seem to apply the class or ID names to the created div. I copied the code exactly too. I saw somewhere else that someone used className:"random" rather than "class" but neither worked. Any ideas? – Carson Aug 05 '10 at 16:32
  • @Carson - I gave the demo a bit of styling for the class here: http://jsfiddle.net/nick_craver/TTHDQ/12/ just replace `wrapper` in my code above with whatever class or classes you want the div to have :) – Nick Craver Aug 05 '10 at 17:35
  • Still couldn't get that working, but I found a workaround for those of you in the same boat. The following adds a class and id to each div created: $('
    ').addClass('product').attr('id', 'product'+i)
    – Carson Aug 05 '10 at 17:50
  • Thanks for the solution, i'm trying using this inconjuction with adding a class style onmouseover and onmouseout, it works in Firefox but is unable to work in IE and Google, would you know how to do it? Here is the code i have used 'code' jQuery("
    ", { "class": "wrapper", id: "product" + i, "onmouseover": "javascript:Highlight(this.id);", "onmouseout": "javascript:Lowlight(this.id);" }) .append(jQuery("", { type: "text", id: "name" + i }))...... 'code'
    – Rav Oct 24 '11 at 10:35
  • @Rav - My guess would be `` is a self-closing or unclosed element, IE may be rejecting it. Also, don'y use strings, just use something like `onmouseover:Highlight` where `Highlight` is your function and just use `this.id` inside of it...since `this` will refer to the `
    ` it happened on.
    – Nick Craver Oct 24 '11 at 10:39
8

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.

rodiwa
  • 1,690
  • 2
  • 17
  • 35
3
$(function(){
    var pcount = icount = 0;

    $('<div/>', {
       id:   'product' + pcount++
    }).append($('<input/>', {
       id:   'input' + icount++
    })).append($('<input/>', {
       id:   'input' + icount++
    })).appendTo(document.body);
});
jAndy
  • 231,737
  • 57
  • 305
  • 359
1

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()

Gareth
  • 133,157
  • 36
  • 148
  • 157
  • He's *probably* submitting the values to a server though :) So generally you do need either an ID or a name :) – Nick Craver Aug 05 '10 at 15:28
  • 1
    IDs aren't anything to do with form submissions, but you're right that a name will need to be generated if that's the case – Gareth Aug 05 '10 at 15:31
0

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.

Adam Pietrasiak
  • 12,773
  • 9
  • 78
  • 91
0

You can used Just increase variable and append to create unique DIV ID Code As like Bellow

var x = 1;
var wrapper = $('.field_wrapper'); //Input field wrapper your div Add in this Class


var fieldtext = '<div ID="product_'+x+'"><label id="label_'+x+'" for="field_'+x+'"></label><input type="text" id="field_'+x+'" name="field_'+x+'" value=""/></div>'; //New input field html 

$(wrapper).append(fieldtext); // Add field html
x++;
Rathod Paresh
  • 221
  • 2
  • 4