views:

104

answers:

3

Hey guys, 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

A: 

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
PS I'm obviously new here so how do you make code look like code haha
Carson
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
@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
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)
Carson
A: 

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
He's *probably* submitting the values to a server though :) So generally you do need either an ID or a name :)
Nick Craver
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
A: 
$(function(){
    var pcount = icount = 0;

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