Issue
I have a boolean field in the database - emails_allowed
. This is reflected in the user profile page as a bootstrap 5 switch input
To represent the current value in the database I am using the template language in the following manner -
<input class="form-check-input" style="margin-left: -1.5em;" type="checkbox"
id="email-allowed"
{{ profile.email_allowed|yesno:"checked,unchecked" }}>
I was expected the template language to merely output checked
or unchecked
as a string. Instead it is creating a HTML attribute called checked
or unchecked
as shown below -
<input class="form-check-input" style="margin-left: -1.5em;" type="checkbox" id="email-allowed" checked="">
As a result, I am unable to change the state of the switch as it is permanently either checked
or unchecked
. Has anyone come across this issue? Any suggestions on how to solve this is greatly appreciated. Thanks in advance
Solution
The behaviour of checkboxes in HTML5 is determined by the existence, or non existence of the checked attribute. You could set it to anything. What values for checked are false and HTML5 specs
Meaning behind the scenes you will always get a HTML attribute. The onClick event will toggle this checked attribute for checkboxes.
The keyword unchecked
doesn't do anything. You could change your template to:
<input class="form-check-input" style="margin-left: -1.5em;" type="checkbox"
id="email-allowed"
{{ profile.email_allowed|yesno:"checked=checked"," }}>
If you want the word "checked" or "unchecked" as a string inside your input element like this:
<input class="form-check-input" style="margin-left: -1.5em;" type="checkbox" id="email-allowed" "checked">
You'll need to change the template to also add the quotaion marks. You'll have to escape them:
<input class="form-check-input" style="margin-left: -1.5em;" type="checkbox"
id="email-allowed"
{{ profile.email_allowed|yesno:"\"checked\",\"unchecked\"" }}>
However i do not reccomend this. Because this is not a valid HTML attribute and doesn't do anything.
Answered By - Martin Achenrainer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.