Skip to content

Commit

Permalink
checkbox: fixed to not require a label for=id attribute if the label …
Browse files Browse the repository at this point in the history
…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.
  • Loading branch information
rdworth committed Apr 8, 2010
1 parent 55dc0bb commit 93c3e89
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
16 changes: 12 additions & 4 deletions tests/visual/checkbox/default.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,29 @@
<script type="text/javascript" src="../../../ui/jquery.ui.checkbox.js"></script>
<script type="text/javascript">
$(function() {
$("#check1, #check2, #check3").checkbox();

$(":checkbox").checkbox();
});
</script>
</head>
<body>

<form>

<input type="checkbox" id="check1" /><label for="check1">Check 1</label>
<label><input type="checkbox" />Check 1</label>

<input type="checkbox" id="check2" /><label for="check2">Check 2</label>
<label><input type="checkbox" id="check2" />Check 2</label>

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

<input type="checkbox" id="check4" /><span><label for="check4">Check 4</label></span>

<table>
<tr>
<td><input type="checkbox" id="check5" /></td>
<td><label for="check5">Check 5</label></td>
</tr>
</table>

</form>

</body>
Expand Down
23 changes: 18 additions & 5 deletions ui/jquery.ui.checkbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,29 @@
*/
(function( $ ) {

var checkboxId = 0;

$.widget( "ui.checkbox", {

_create: function() {

// find the checkbox's label
this.labelElement = $( this.element[0].ownerDocument ).find( "label[for=" + this.element.attr("id") + "]" );

// move the checkbox outside (before) the label if it's inside it
if ( this.labelElement.has(this.element).length ) {
// look for label as container of checkbox
this.labelElement = this.element.closest( "label" );
if ( this.labelElement.length ) {
// move the checkbox outside (before) the label
this.element.insertBefore( this.labelElement );

// the checkbox needs an id since it's no longer inside the label
if ( !this.element.attr( "id" ) ) {
this.element.attr( "id", "ui-checkbox-" + checkboxId );
checkboxId += 1;
}

// associate label by for=id of checkbox
this.labelElement.attr( "for", this.element.attr("id") );
} else {
// look for label by for=id of checkbox
this.labelElement = $( this.element[0].ownerDocument ).find( "label[for=" + this.element.attr("id") + "]" );
}

// wrap the checkbox in a new div
Expand Down

0 comments on commit 93c3e89

Please sign in to comment.