Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox checked attribute not working with Pug

I have the following checkbox written in Pug:

 input(id="favorite" type="checkbox" name="favorite" value='true' checked='#{item.favorite ? true : false}')

When I inspect the item I can see that the logic for the checked attribute is working, showing true or false depending on the situation, but no matter if it is true or false, the checkbox is always selected.

I think the issue might be that, because of #{item.favorite ? true : false} is between quotes, the result is not being treated as boolean but as a string. But if I write the code with out quotes it does not work.

My question is, how should I write this so the checked attribute reads the result as boolean?

like image 727
Carlos G Avatar asked Oct 16 '25 01:10

Carlos G


1 Answers

As outlined in the manual section about attributes this can be achieved by

input(checked=item.favorite id="favorite" type="checkbox" name="favorite" value="true")

If item.favorite is a falsey value, checked is omitted.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!