How to keep checkbox values on form validation. #3817
-
It has been awhile since I have used AdonisJS (several years) but I have recently started using it again on a couple projects. I am currently trying to build a simple form with validation. I have the flash messages set up and I am able to get it working properly with text inputs but I am wondering how to keep the old values when I have checkboxes. Is it possible to loop over my checkbox values that are stored in the flash message? Here is an example of what I have: {
"values": {
"firstName": null,
"lastName": null,
"email": null,
"phone": null,
"serveFrequency": [
'Once a month',
'Twice a month'
],
} and this is how I am currently handling it in the template. <div class="sp-fieldset required " data-type="checkbox">
<div class="sp-field-col">
<label class="sp-field-label">How often would you like to serve?</label><br><input name="serveFrequency"
type="checkbox" class="sp-field-checkbox" value="Once a month" {{(flashMessages.get('serveFrequency') === 'Once a month' || flashMessages.get('serveFrequency[0]' === 'Once a month')) ? "checked=true" : null }}>
<label>Once a month</label><br><input name="serveFrequency" type="checkbox" class="sp-field-checkbox"
value="Twice a month" {{(flashMessages.get('serveFrequency') === 'Twice a month' || flashMessages.get('serveFrequency[0]') === 'Twice a month' || flashMessages.get('serveFrequency[1]') === 'Twice a month') ? "checked=true" : null }}>
<label>Twice a month</label><br>
@if(flashMessages.has('errors.serveFrequency'))
<div class="error">Please choose how often you would like to serve</div>
@end
</div>
</div> Surely there is a better way to do this? The problem is I have another field with about 6 checkboxes and multiple ones could be checked. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
What is the issue you are facing? |
Beta Was this translation helpful? Give feedback.
-
You can use But you can use - flashMessages.get('serveFrequency') === 'Twice a month' || flashMessages.get('serveFrequency[0]') === 'Twice a month' || flashMessages.get('serveFrequency[1]') === 'Twice a month'
+ flashMessages.get('serveFrequency').includes('Twice a month') On why |
Beta Was this translation helpful? Give feedback.
You can use
in
? Edit : noBut you can use
includes
On why
serveFrequency
could be a string or an array ? I think a use can choose only one, once a month OR twice a month, so maybe radio input could be better.