Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 282
user3162553 Avatar asked Jul 28 '26 19:07

user3162553


1 Answers

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);
like image 85
Salman A Avatar answered Jul 30 '26 10:07

Salman A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!