Opened 2 years ago

Closed 2 years ago

#27250 closed Bug (fixed)

Confusing <label> assignment with CheckboxSelectMultiple

Reported by: Daniel Lamprecht Owned by: MartinArroyo
Component: Forms Version: master
Severity: Normal Keywords: CheckboxSelectMultiple label
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


Using CheckboxSelectMultiple leads to a (in my opinion) confusing assignment of the <label> in the generated HTML. The general label for the choices refers to the first element in the list. Please see this example:

class TestForm(forms.Form):
    days = forms.MultipleChoiceField(
        choices=[('1', 'DayOne'), ('2', 'DayTwo')],

def form(request):
    return render(request, 'form.html', {'form': forms.TestForm()})


<form method="post">
    {{ form.as_ul }}
  <button type="submit">Submit</button>

Resulting HTML (prettified):

<form method="post">
      <label for="id_days_0">Days:</label>
      <ul id="id_days">
          <label for="id_days_0"><input id="id_days_0" name="days" type="checkbox" value="1" /> DayOne</label>
          <label for="id_days_1"><input id="id_days_1" name="days" type="checkbox" value="2" /> DayTwo</label>
  <button type="submit">Submit</button>

This means that clicking on "Days" selects the first day. I would suggest to remove the "<label> element and only keep the label text itself.

Compare this to the HTML when not having the CheckboxSelectMultiple widget, where clicking on "Days" simply selects the <select> element:

<form method="post">
      <label for="id_days">Days:</label>
      <select multiple="multiple" id="id_days" name="days" required>
        <option value="1">One</option>
        <option value="2">Two</option>
  <button type="submit">Submit</button>

Change History (7)

comment:1 Changed 2 years ago by Simon Charette

Keeping the label but removing the for attribute seems like safer option to me.

comment:2 Changed 2 years ago by Claude Paroz

Triage Stage: UnreviewedAccepted
Version: 1.10master

+1 for removing the for attribute.

comment:3 Changed 2 years ago by MartinArroyo

Owner: changed from nobody to MartinArroyo
Status: newassigned

comment:4 Changed 2 years ago by MartinArroyo

Needs tests: set

comment:5 Changed 2 years ago by Tim Graham

Has patch: set
Needs tests: unset
Patch needs improvement: set

PR with some comments for improvement.

comment:6 Changed 2 years ago by Tim Graham

Patch needs improvement: unset

comment:7 Changed 2 years ago by Tim Graham <timograham@…>

Resolution: fixed
Status: assignedclosed

In abd43405:

Fixed #27250 -- Removed 'for ="..."' from CheckboxSelectMultiple's <label>.

Note: See TracTickets for help on using tickets.
Back to Top