user3162553
user3162553

Reputation: 2859

How can I dynamically create input elements with different Ids?

I have inputs that I dynamically generate with JavaScript. However, I'm unsure of how it is possible to add ids to those. Let me be clear: I want different ids for each, I know how to add just one id for all of them.

This is what I've tried:

$(document).ready(function() { 
var wrapper         = $(".wayptHolder");      //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID
var x               = 0;                      //initial text box count

//add input element 
$(add_button).click(function(event){          
    event.preventDefault();
    if(x < 8){ 

      $(wrapper).append('<div><input type="text", id="waypt"' + x + ' class="form-control added-input", placeholder="Next"><a href="#" class="remove_field">Remove</a></div>');//add inputbox
        x++;
     }
});


    $(wrapper).on("click",".remove_field", function(event){ //user click on remove text
        event.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

However, on the new element, it shows the id as just waypt. I've researched and it doesn't look like JavaScript has string interpolation. Ruby for example, solves this problem with being able to have waypt#{x} so that the string interprets x as a variable. How can JS replicates this behavior?

Upvotes: 3

Views: 122

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272056

Your double quotes are not closed properly:

$(wrapper).append('<input type="text", id="waypt"' + x + ' class="...

Would result in the following HTML:

<input type="text", id="waypt" 0 class="...
<input type="text", id="waypt" 1 class="...

The obvious solution is to fix the quotes (and get rid of commas):

$(wrapper).append('<input type="text" id="waypt' + x + '" class="...

However, I would recommend something like:

var $div = $("<div>");
$("<input>", {
    "type": "text",
    "id": "waypt" + x,
    "class": "form-control added-input",
    "placeholder": "Next"
}).appendTo($div);
$("<a></a>", {
    "href": "#",
    "class": "remove_field"
}).text("Remove").appendTo($div);
$div.appendTo(wrapper);

Upvotes: 7

Avi
Avi

Reputation: 1964

Not sure I understand you correctly but if generating Id's is what you are after, try this:

var date = new Date();
var ticks = date.getTime();

now ticks will give you a very unique number that you can concatenate to your id:

id = "waypt"+ticks;

hope it helps

Upvotes: 0

Related Questions