Skip to content

Commit 93c3e89

Browse files
committed
checkbox: fixed to not require a label for=id attribute if the label contains the checkbox. An id is generated if the checkbox doesn't have one since we move the checkbox out of the label in this case for consistent markup.
1 parent 55dc0bb commit 93c3e89

File tree

2 files changed

+30
-9
lines changed

2 files changed

+30
-9
lines changed

tests/visual/checkbox/default.html

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,21 +11,29 @@
1111
<script type="text/javascript" src="../../../ui/jquery.ui.checkbox.js"></script>
1212
<script type="text/javascript">
1313
$(function() {
14-
$("#check1, #check2, #check3").checkbox();
15-
14+
$(":checkbox").checkbox();
1615
});
1716
</script>
1817
</head>
1918
<body>
2019

2120
<form>
2221

23-
<input type="checkbox" id="check1" /><label for="check1">Check 1</label>
22+
<label><input type="checkbox" />Check 1</label>
2423

25-
<input type="checkbox" id="check2" /><label for="check2">Check 2</label>
24+
<label><input type="checkbox" id="check2" />Check 2</label>
2625

2726
<input type="checkbox" id="check3" /><label for="check3">Check 3</label>
2827

28+
<input type="checkbox" id="check4" /><span><label for="check4">Check 4</label></span>
29+
30+
<table>
31+
<tr>
32+
<td><input type="checkbox" id="check5" /></td>
33+
<td><label for="check5">Check 5</label></td>
34+
</tr>
35+
</table>
36+
2937
</form>
3038

3139
</body>

ui/jquery.ui.checkbox.js

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,29 @@
1515
*/
1616
(function( $ ) {
1717

18+
var checkboxId = 0;
19+
1820
$.widget( "ui.checkbox", {
1921

2022
_create: function() {
2123

22-
// find the checkbox's label
23-
this.labelElement = $( this.element[0].ownerDocument ).find( "label[for=" + this.element.attr("id") + "]" );
24-
25-
// move the checkbox outside (before) the label if it's inside it
26-
if ( this.labelElement.has(this.element).length ) {
24+
// look for label as container of checkbox
25+
this.labelElement = this.element.closest( "label" );
26+
if ( this.labelElement.length ) {
27+
// move the checkbox outside (before) the label
2728
this.element.insertBefore( this.labelElement );
29+
30+
// the checkbox needs an id since it's no longer inside the label
31+
if ( !this.element.attr( "id" ) ) {
32+
this.element.attr( "id", "ui-checkbox-" + checkboxId );
33+
checkboxId += 1;
34+
}
35+
36+
// associate label by for=id of checkbox
37+
this.labelElement.attr( "for", this.element.attr("id") );
38+
} else {
39+
// look for label by for=id of checkbox
40+
this.labelElement = $( this.element[0].ownerDocument ).find( "label[for=" + this.element.attr("id") + "]" );
2841
}
2942

3043
// wrap the checkbox in a new div

0 commit comments

Comments
 (0)