How do I get the value of a DOM element from an encapsulated JavaScript object? This does not work. I get nothing as in undefined. I thought the page wasn't rendering and thus couldn't be seen, but I put it in the .ready function and I continue to get undefined.
$(document).ready(function() {
GetLoans = {
myModal: function() {
return document.querySelector("#myModal")
},
myModalBody: function() {
return document.querySelector(".modal-body")
},
getNewLoans: function() {
var xhr;
xhr = new XMLHttpRequest();
var url = "/api/books";
xhr.open("GET", url, true);
xhr.responseType = 'json';
xhr.send(null); //or your data
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200)) {
var result = xhr.response;
for (var key in result) {
if (result.hasOwnProperty(key)) {
//console.log(result[key].patron_id);
this.myModalBody.innerHTML = result[key].patron_id;
}
}
}
}
// var serverResponse = xhr.responseText;
// this.myModalBody.innerHTML = serverResponse;
},
bindUIActions: function() {
// this.myModalBody.addEventListener("click", this.getNewLoans(), false);
},
init: function() {
this.getNewLoans();
//this.bindUIActions();
}
};
GetLoans.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Uncaught TypeError: Cannot set property 'innerHTML' of undefined
at XMLHttpRequest.xhr.onreadystatechange
No jQuery please (yes, I know I am using the Document.Ready function.)