Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #3312 -- CheckboxSelectMultiple no longer uses duplicate ID att…

…ributes for each checkbox

git-svn-id: http://code.djangoproject.com/svn/django/trunk@4436 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit c0e01416b68e482172ef23cc507f163b873c192a 1 parent 982a944
Adrian Holovaty authored January 27, 2007
9  django/newforms/widgets.py
@@ -258,11 +258,16 @@ def id_for_label(self, id_):
258 258
 class CheckboxSelectMultiple(SelectMultiple):
259 259
     def render(self, name, value, attrs=None, choices=()):
260 260
         if value is None: value = []
  261
+        has_id = attrs and attrs.has_key('id')
261 262
         final_attrs = self.build_attrs(attrs, name=name)
262 263
         output = [u'<ul>']
263 264
         str_values = set([smart_unicode(v) for v in value]) # Normalize to strings.
264  
-        cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
265  
-        for option_value, option_label in chain(self.choices, choices):
  265
+        for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
  266
+            # If an ID attribute was given, add a numeric index as a suffix,
  267
+            # so that the checkboxes don't all have the same ID attribute.
  268
+            if has_id:
  269
+                final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
  270
+            cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
266 271
             option_value = smart_unicode(option_value)
267 272
             rendered_cb = cb.render(name, option_value)
268 273
             output.append(u'<li><label>%s %s</label></li>' % (rendered_cb, escape(smart_unicode(option_label))))
10  tests/regressiontests/forms/tests.py
@@ -2149,6 +2149,16 @@
2149 2149
 <li><label><input checked="checked" type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
2150 2150
 </ul>
2151 2151
 
  2152
+Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox
  2153
+gets a distinct ID, formed by appending an underscore plus the checkbox's
  2154
+zero-based index.
  2155
+>>> f = SongForm(auto_id='%s_id')
  2156
+>>> print f['composers']
  2157
+<ul>
  2158
+<li><label><input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li>
  2159
+<li><label><input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li>
  2160
+</ul>
  2161
+
2152 2162
 Data for a MultipleChoiceField should be a list. QueryDict and MultiValueDict
2153 2163
 conveniently work with this.
2154 2164
 >>> data = {'name': 'Yesterday', 'composers': ['J', 'P']}

0 notes on commit c0e0141

Please sign in to comment.
Something went wrong with that request. Please try again.