Mutasim Fuad
Mutasim Fuad

Reputation: 606

Use variable inside a string in Javascript

I am trying to add some DOM when click in a button. But i want to add the name attribute dynamically. Here is my code

$(document).ready(function() {
                console.log("done");
                var counterEdu = 1;
                $("#add-edu").click(function (event) {
                    event.preventDefault();
                    counterEdu  = counterEdu+1;    
                    $("#passing-year").after('<div class="col-md-12 form-group1">'+'<input type="text" placeholder="Degree Name" name="degree"+counterEdu;>'

                });
            });

I want to add the name attribute concatenated with

counterEdu

variable. like degree1,degree2..... so how to do that?

Upvotes: 0

Views: 61

Answers (2)

YounesM
YounesM

Reputation: 2317

Since counterEdu is not a string

$(document).ready(function() {
            console.log("done");
            var counterEdu = 1;
            $("#add-edu").click(function (event) {
                event.preventDefault();
                counterEdu  = counterEdu+1;    
                $("#passing-year").after('<div class="col-md-12 form-group1">'+'<input type="text" placeholder="Degree Name" name="degree'+counterEdu+'">'

            });
        });

Upvotes: 1

Ionut Necula
Ionut Necula

Reputation: 11472

You need to escape it properly:

$("#passing-year").after('<div class="col-md-12 form-group1">' + '<input type="text" placeholder="Degree Name" name="degree'+counterEdu +'">'

Upvotes: 2

Related Questions