How can I dynamically create input elements with different IDs?

I have inputs that I generate dynamically using JavaScript. However, I'm not sure how I can add IDs to them. Let me be clear: I need different IDs for each, I know how to add only one ID for all of them.

Here's 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, in the new element, it shows the id as just waypt. I researched and it doesn't seem like JavaScript has string interpolation. Ruby, for example, solves this problem by being able to have a waypt # {x} to make the string interpret x as a variable. How can JS reproduce this behavior?

+3


source to share


2 answers


Your double quotes are not properly closed:

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

      

The following HTML will appear:

<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 the 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);

      

+7


source


Not sure if I understand you correctly, but if generating Id is what you want, try this:

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

      

now ticks will give you a unique number that you can associate with your id:



id = "waypt"+ticks;

      

hope this helps

0


source







All Articles