so i have a Community schema that contains name and departments, the departments field has a type array..how to do i render the departments in a dropdownlist dependent on the name field.
this is my routes.js
router.get('/setup', (req, res,next) => {
Community.find(function(err, data) {
res.render('setup', {
community: data,
});
});
});
this is my Community schema
const CommunitySchema = new mongoose.Schema({
name: {
type: String
},
department: [{
type: String
}]
});
and this is my setup.ejs
<label for="fullname"><strong>What department do you belong to ?</strong></label>
<select class="form-control" id="community" name="community">
<optgroup label="Select Table">
<% community.forEach(function (practice) { %>
<option > <%= practice.department.pop() %> </option>
<% }) %>>
</optgroup>
</select>
**this is the data **
{
"name":"Engineering",
"departments":[ "Electrical engineering", "Mechanical engineering", "Chemical engineering" ]
},
{
"name":"Arts",
"departments":[ "Philosophy", "Theatre arts", "English" ]
}
i am trying to make a dependent dropdownlist, i hope my question was understood
Do not perform pop
operation on your array,
Try this way, code might give syntactical errors but idea is that you should loop over your departments
array to create options inside select
element.
<label for="fullname"><strong>What department do you belong to ?</strong></label>
<select class="form-control" id="community" name="community">
<optgroup label="Select Table">
<% community.forEach(function (practice) { %>
<% practice.departments.forEach(function (dept) { %>
<option> <%= dept %> </option>
<% }) %>>
<% }) %>>
</optgroup>
</select>
.
(my assumption below)
I'm not sure about what is the expected output in your question but I think your expecting something like below in your select dropdown, if yes, then above code wont give the result.
|- Engineering
|--- Electrical engineering
|--- Mechanical engineering
|--- Chemical engineering
|- Arts
|--- Philosophy
|--- Theatre arts
|--- English
use following
<label for="fullname"><strong>What department do you belong to ?</strong></label>
<select class="form-control" id="community" name="community">
<% community.forEach(function (practice) { %>
<optgroup label="<%= practice.name %>">
<% practice.departments.forEach(function (dept) { %>
<option> <%= dept %> </option>
<% }) %>>
</optgroup>
<% }) %>>
</select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.