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

2
  • What are you using these dynamic IDs for? Commented Aug 5, 2010 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. Commented Aug 6, 2010 at 15:19

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

6 Comments

PS I'm obviously new here so how do you make code look like code haha
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 - I gave the demo a bit of styling for the class here: jsfiddle.net/nick_craver/TTHDQ/12 just replace wrapper in my code above with whatever class or classes you want the div to have :)
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: $('<div />').addClass('product').attr('id', 'product'+i)
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("<div></div>", { "class": "wrapper", id: "product" + i, "onmouseover": "javascript:Highlight(this.id);", "onmouseout": "javascript:Lowlight(this.id);" }) .append(jQuery("<input></input>", { type: "text", id: "name" + i }))...... 'code'
|
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.

2 Comments

One note, this method is available from jQuery 1.9
Thanks for showing a different but interesting way.
3
$(function(){
    var pcount = icount = 0;

    $('<div/>', {
       id:   'product' + pcount++
    }).append($('<input/>', {
       id:   'input' + icount++
    })).append($('<input/>', {
       id:   'input' + icount++
    })).appendTo(document.body);
});

Comments

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

2 Comments

He's probably submitting the values to a server though :) So generally you do need either an ID or a name :)
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
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.

Comments

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++;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.