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

How to dinamically set a data-target id?

This is an ajax call that write a date from database and put a description in a modal view; so I have 3 modal div myModal0, myModal1,myModal2.
In my problem i want to cancatenate myModal+i but i don't know how to do put it in the data-target id. Please help me.

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