Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Dynamic div with unique IDs - jQuery

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

like image 321
Carson Avatar asked Aug 05 '10 15:08

Carson


People also ask

How to create div id Dynamically in jQuery?

jQuery example to dynamically add a div on page In this example, we have a div with id board and a button to add new divs into this board. In $(document). ready() we have bound an event listener to click event, which means when the user will click on this button, new divs will be created and added into the board.

How do you make a Div unique?

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 })) .


2 Answers

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.

like image 94
Nick Craver Avatar answered Sep 28 '22 10:09

Nick Craver


$(function(){
    var pcount = icount = 0;

    $('<div/>', {
       id:   'product' + pcount++
    }).append($('<input/>', {
       id:   'input' + icount++
    })).append($('<input/>', {
       id:   'input' + icount++
    })).appendTo(document.body);
});
like image 29
jAndy Avatar answered Sep 28 '22 10:09

jAndy