Search code examples
htmlperlmojolicious

checking checkboxes with Mojolicious


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.


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) : ()) %>