javascript - How can I dynamically create input elements with different Ids? -


i have inputs dynamically generate javascript. however, i'm unsure of how possible add ids those. let me clear: want different ids each, know how add 1 id of them.

this 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 new element, shows id waypt. i've researched , doesn't javascript has string interpolation. ruby example, solves problem being able have waypt#{x} string interprets x variable. how can js replicates behavior?

your double quotes not closed properly:

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

would result in following html:

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

the obvious solution fix quotes (and rid of commas):

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

however, recommend 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); 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -