This code works properly:
$(document).ready(function () {
$.getJSON('./record.json', function (data) {
var studentsHTML = '<ul>';
$.each(data, function (index, student) {
studentsHTML +='<li>' + student.name + '</li>';
});
studentsHTML += '</ul>';
$('#students').html(studentsHTML);
});
});
But this doesn’t:
$(document).ready(function () {
$.getJSON('./record.json', function (data) {
var studentsHTML = '<ul>';
$.each(data, function (index, student) {
studentsHTML +='<li onclick="showSubject(' + student.subject + ')">' + student.name + '</li>';
});
studentsHTML += '</ul>';
$('#students').html(studentsHTML);
});
function showSubject(subj) {
alert(subj);
}
});
It gives the error message:
"ReferenceError: showSubject is not defined"
A simple alert() function works, but only with the ‘index’ parameter:
onclick="alert(' + index + ')"
It shows the indexes of the items properly. But nothing else. Eg.: alert does not work with "student.subject" too.
Is there a way to make my list elements clickable?
3
Answers
The issue stated is
so the onclick= is not able to find your function.
When you use
onclick=
with a function, that function must be defined as a global. Defining it within the doc.ready block makes it only available within that doc.ready block, it’s not global, so onclick can’t find itMove the function outside of doc.ready and it will find it.
There is also an error with missing quotes, around the argument, added in the snippet below.
As a bonus, the recommend way to do this is with event delegation:
Problem you have is the scope of the function and not quoting the value inside the function call. It is better to not use inline events, but to bind event listeners to the element.
You would be better off using event delegation and data attributes
inspect the li element on which you have added the onclick event.
Your onclick look like this:-
showSubject(‘Math’)
Not like this:-
showSubject(Math)
the fix would be properly escape the quotes as shown by freedomn-m
and it should work