Reputation: 95
I have a dynamically generated table based on the size of the JSON response from my AJAX call. What I want to do is to have a modal that displays additional data when clicking on a table row. This would be easy to do if it is hard coded, but seeing how data on my page is generated whenever the page is reloaded by calling the database, I can't seem to figure out how to pass the data to the modal.
So far I have tried having a single modal and then use .addAttribute
and .appendChild
to pass information to the modal but this is not working and the modal is blank. I suspect it is due to the fact that the modal is loaded at the same time as the page, so it never gets populated even if I click the button.
My modal:
<div id="modalDisplay" class="modal">
<div id="modalDisplayContent" class="modal-content">
<span class="close" onclick="onClickGetSpan()">×</span>
<div id="formDisplayContent" class="modalContent">
</div>
</div>
</div>
My function that gets called whenever a table row is clicked:
function getSingleTask(id){
var taskName = "";
var taskDescription = "";
$.ajax(
{
url: "http://localhost:8080/tasks/" + id,
type: "GET",
dataType: "JSON",
success: function(){
taskName = data.name;
taskDescription = data.description;
var nameTitle = document.createElement("H2");
nameTitle.setAttribute("value", name);
var description = document.createElement("P");
description.setAttribute("value", taskDescription);
document.getElementById("formDisplayContent").appendChild(nameTitle);
document.getElementById("formDisplayContent").appendChild(description);
},
error: function () {
var noNameTitle = document.createElement("H2");
noNameTitle.setAttribute("value", "Error finding task! Try again!");
document.getElementById("formDisplayContent").appendChild(noNameTitle);
}
}
)
var modal = document.getElementById("modalDisplay");
modal.style.display = "block";
}
I could always create modals together with my table for every row, have them sorted by IDs and then open the corresponding modal when a table row is clicked. But before I dwell into that, I wanted to see if anyone can come up with a better solutions maybe involving my current approach. Thanks in advance.
Upvotes: 1
Views: 339
Reputation: 478
Here my usual code:
<div id="myModal" class="modal">
<div id="modal-dialog" class="modal-content">
<span class="btn"></span><br/>
<span id="changethis"></span>
</div>
</div>
function btnFromTableRows() {
$.ajax( {
url: "http://localhost:8080/main/",
type: "GET",
dataType: "JSON",
success: function(){
mydata = "<div class='container'>This is a sample container</div>";
document.getElementById("changethis").innerHTML = mydata;
},
error: function () {
mydata = "<h2>Invalid data</h2>";
document.getElementById("changethis").innerHTML = mydata;
}
}
}
Upvotes: 1