Ian Hoar
Ian Hoar

Reputation: 1184

jQuery Mobile, show/hide checkbox/radio and update displayed inputs

I'm trying to dynamically add and remove inputs from a checkbox group. The example below works, but when the input is removed I don't get rounded edges anymore on the last input item. It just cuts off. I thought running a checkboxradio('refresh') would rectify the issues, but it hasn't. Any ideas?

if(some condition) {
  $('.hideThis').hide();
  $('[name=values]').checkboxradio('refresh');
} else {
    $('.hideThis').show();
    $('[name=values]').checkboxradio('refresh');
}

<div data-role="fieldcontain">
    <fieldset data-role="controlgroup">
        <input type="checkbox" name="values" id="val1" value="val1">
        <label for="val1">Value 1</label>
        <input type="checkbox" name="values" id="val2" value="val2">
        <label for="val2">Value 2</label>
        <div class="hideThis">
            <input type="checkbox" name="values" id="val3" value="val3">
            <label for="val3">Value 3</label>
        </div>
    </fieldset>
</div>

Upvotes: 1

Views: 2775

Answers (1)

Omar
Omar

Reputation: 31732

Update

Based on the OP comment, the answer below works for Jquery Mobile V1.3.0.

For Jquery Mobile V1.2.0, instead of ui-last-child class, use ui-corner-bottom and ui-controlgroup-last classes for the last checkbox.

Original answer "Jquery Mobile V1.3.0"

Last checkbox has ui-last-child styling. So when you hide/remove the last checkbox, JQM doesn't add that class to the previous checkbox. Therefore, you have to work your way through, by adding ui-last-child style to the previous checkbox of the hidden one.

If you hide the first checkbox, use ui-first-child instead.

Markup

<a href="#" data-role="button" id="hidethis">hide this</a>

<form>
 <fieldset data-role="controlgroup">
    <legend>Vertical:</legend>
    <input type="checkbox" name="checkbox-v-2a" id="checkbox-v-2a">
    <label for="checkbox-v-2a">One</label>
    <input type="checkbox" name="checkbox-v-2b" id="checkbox-v-2b">
    <label for="checkbox-v-2b">Two</label>
    <input type="checkbox" name="checkbox-v-2c" id="checkbox-v-2c">
    <label for="checkbox-v-2c">Three</label>
 </fieldset>
</form>

JQM

$(document).on('click', 'a#hidethis', function () {
 $('div.ui-checkbox:last-child').prev('div').find('label').addClass('ui-last-child');
 $('div.ui-checkbox:last-child').hide();
});

JSFiddle Example

Upvotes: 4

Related Questions