D. belvedere D. belvedere - 1 month ago 7
HTML Question

How to dynamically set a data-target id?

I have three div's with different IDs. I would like to concatenate

myModal + i
into the
data-target
attribute, but I am unsure of how to do it. Here is my code:

success: function (response) {
var work;
var res = response.split("ยง");
var modalid;
for (var i = 0; i < res.length - 1; i++) {
modalid = "myModal" + i;
work = res[i].split("^");
document.getElementById('eventi').innerHTML += "Cena del: " + work[0] + "<button type=\"button\" data-toggle=\"modal\" data-target=\"#\"\">leggi di piu</button>" + "<br>";
document.getElementById('description' + (i)).innerHTML = work[1];
}
}

Answer

With ES5 String concatenation

I've changed the wrapping quotes to single quotes to prevent the need to escape internal quotes.

document.getElementById('eventi').innerHTML +=
  'Cena del: ' + work[0] + '<button type="button" data-toggle="modal" data-target="#' + modalid + '">leggi di piu</button><br>';
Comments