Reputation: 507
I'm kind of new at Express/Jade, so apologies if this is a dumb question.
I'm passing JSON data in to a Jade template, but, though the data is definitely there and usable elsewhere on the page, I can't seem to access it in a Javascript function within the same page.
The code in question looks like this:
script.
function populateData(value){
console.log("Value = " + value);
for(i = 0;i <= 3;i++){
console.log("i = " + i);
if(value==i){
console.log("school = " + mydata.sclist[i].sName);
$('#input_sid').val(mydata.sclist[i].sID);
$('#input_spc').val(mydata.sclist[i].sPostcode);
}
}
}
form#form_add_booking(name="addbooking",method="post",action="/addbooking")
table.formtable
tr
td
span
b School Name
td
select#input_sname(name="sname" onChange="populateData(this.value)")
option.
====== select ======
each school, i in mydata.sclist
option(value=i).
#{school.sName}
So, in the above code the SELECT list gets correctly populated with school names from the JSON, but, when the onChange attribute fires the Javascript function, I get an 'Uncaught ReferenceError that 'mydata' is not defined.
What am I missing please?
Upvotes: 0
Views: 49
Reputation: 1049
I assume mydata
is passed to jade when rendering the page. The page is then returned from the server to the client (web browser) as rendered HTML. You can't then access mydata
variable because it's used only on server-side to render the page. (Select is rendered on serve-side)
To be able to access the data the way you want, you'll have to render javascript variable in addition to your code above which can then be used on the client-side. (when select is changed)
const clientSideData = !{(JSON.stringify(mydata))};
Place this to very top of populateData
(it converts JSON object to string) and then replace mydata
references in the function with clientSideData
. In this way you'll have access to the data even from client-side as you'll render javascript variable.
Upvotes: 1