Setting Checkbox State with jQuery Mobile

Ajax, Javascript, JQuery, jQuery Mobile, Pebblet

I used jQuery Mobile to create the UI for the Mobile Theme Generator. One of the processes that had to be frequently coded was setting the state of the jQuery Mobile checkbox. Because of the many classes associated with displaying a mobile checkbox, the code was more involved that I first anticipated.

To set checkbox state to ‘on’:

var c = $('#mycheckbox');
$(c).attr({'checked': true, 'data-icon': 'checkbox-on'}).siblings('label').removeClass('ui-checkbox-off').addClass('ui-checkbox-on');
c = $(c).siblings('label').children('span').children('span')[1];

I first set the “checked” attribute to true and also set the “data-icon” attribute to ‘checkbox-on’.
I changed the class for the checkbox label from ‘ui-checkbox-off’ to ‘ui-checkbox-on’.
I then get the sibling label for the checkbox so that I can get the second ‘grand-child’ of the label. I change the class of the span from ‘ui-icon-checkbox-off’ to ‘ui-icon-checkbox-on’.

<div class="ui-checkbox">
    <label for="mycheckbox" data-corners="true" data-shadow="false" data-iconshadow="true" data-wrapperels="span" data-icon="checkbox-off" data-theme="a" data-mini="true" class="ui-btn ui-btn-corner-all ui-mini ui-btn-icon-left ui-checkbox-off ui-btn-up-a">
        <span class="ui-btn-inner ui-btn-corner-all">
            <span class="ui-btn-text">Menu Items Mini:</span>
            <span class="ui-icon ui-icon-shadow ui-icon-checkbox-off">&nbsp;</span>
    <input type="checkbox" name="mycheckbox" id="mycheckbox" data-mini="true">

That’s it. Of course, to turn it back off, I just to change to classes back (and removed the ‘checked’ attribute).

Checkout My New Site - T-shirts For Geeks