Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

checking checkboxes with Mojolicous

I want create a checkbox group and need to check some checkboxes.

$user is a list of all "Users". The method $activity->users(u_id) check if the user is "active" and return 1/0. But it doesn’t matter what it return, the checkbox is always checked if I use this code:

% $user->foreach( sub {
% my $checked = $activity->users($_[0]->u_id) ? 'checked' : '';
 <span><%= check_box 'users' => $_[0]->u_id, checked => $checked  %>
 %= $_[0] 
 %= $checked
 </span>
 % });

The documentation unfortunatly doesn’t explain how it is right and I also didn’t found any other site which explain how it should be.
https://docs.mojolicious.org/Mojolicious/Plugin/TagHelpers#check_box

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In HTML, as long as a checkbox (by "checkbox" I mean "input with checkbox type") has a checked attribute, the checkbox will be checked, regardless of the value of the checked attribute.

So, if you don’t want the checkbox to be checked, you should create it without a checked attribute. For instance:

% if ($activity->users($_[0]->u_id)) {
  <span><%= check_box 'users' => $_[0]->u_id, checked => 1  %>
% } else {
  <span><%= check_box 'users' => $_[0]->u_id %>
% }

Or, more concise and with less duplication, but a bit less readable in my opinion:

% my $checked = $activity->users($_[0]->u_id);
<span><%= check_box 'users' => $_[0]->u_id, ($checked ? ('checked' => 1) : ()) %>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading