I want to set a checkbox's 'checked' attribute based whether the category id exists in an articles category array.
each category in the categories object has the fields '_id' and 'name', example: { _id: 12, name: Preparations }
articles.categories is an array of id's, example: [1, 12, 22]
This is what I have now:
- categories.forEach(function(category) {
- var check = 'false'
- article.categories.forEach(function(id) {
- if(id === category._id) {
- check = 'true'
- }
- });
- if(check == 'true') {
li: label.checkbox
input(type="checkbox", name="categories", checked, value=category._id)
=category.name
- } else {
li: label.checkbox
input(type="checkbox", name="categories", value=category._id)
=category.name
- }
- });
The data being passed in is correct and it is iterating through the correct values, I just need to be able to set the checked attribute based on a match. Thanks.
I did something like this few days ago. What I did is assign a boolean value to the 'checked' attribute. See code below. Note that I changed your check variable from string to boolean. I also removed the if-then-else statement.
- categories.forEach(function(category) {
- var check = false
- article.categories.forEach(function(id) {
- if(id === category._id) {
- check = true
- }
- });
li: label.checkbox
input(type="checkbox", name="categories", checked=check, value=category._id)
=category.name
- });
Can also use indexOf (at least since node > 0.5.1)
input(type="checkbox", name="categories", checked=article.categories.indexOf(category._id) !=-1)