I cannot find the mistake here.

jsFiddle --> http://jsfiddle.net/bagofmilk/472s8/

I simply want to make it so that:

Scenario 1:
- User checks a bunch of checkboxes.
- User checks "I hate fruit"
- All other checkboxes are un-checked except for "I Hate Fruit"

Scenario 2:
- User already has "I Hate Fruit" checked.
- User clicks any other checkbox.
- The checkbox "I Hate Fruit" is automatically unchecked.

HTML:

<div data-role='page' id='page1'>
 <section id='squestion2c' class='quest'>
    <h4>What are your Favorite Fruits?</h4>
    <span style='font-style:italic;'> (check all that apply)</span>

    <input type='checkbox' class='fruits' id='apples' name='favoriteFruits' data-mini='true'/>
    <label for='apples'>Apples</label>
    <input type='checkbox' class='fruits' id='bananas' name='favoriteFruits' data-mini='true'/>
    <label for='bananas'>Bananas</label>
    <input type='checkbox' class='fruits' id='canteloupe' name='favoriteFruits' data-mini='true'/>
    <label for='canteloupe'>Canteloupe</label>
    <input type='checkbox' class='fruits' id='strawberries' name='favoriteFruits' data-mini='true'/>
    <label for='strawberries'>Strawberries</label>
    <input type='checkbox' class='fruits' id='raspberries' name='favoriteFruits' data-mini='true'/>
    <label for='raspberries'>Raspberries</label>
    <input type='checkbox' class='fruits' id='blueberries' name='favoriteFruits' data-mini='true'/>
    <label for='blueberries'>Blueberries</label>
    <input type='checkbox' class='fruits' id='hatefruit' name='favoriteFruits' data-mini='true'/>
    <label for='hatefruit'>I Hate Fruit</label>
  </section>
</div>

jquery:

$(document).ready(function() {

  $(".fruits").change(function() {
    if ($('#hatefruit').is(":checked")) {
       $('.fruits').prop('checked', false);
       $('#hatefruit').prop('checked', 'checked');
    } else {
       $('#hatefruit').prop('checked', false);
    }
  });

});
有帮助吗?

解决方案

First of all, you shouldn't use .ready() in jQuery Mobile. Secondly, when you check/uncheck a checkbox or radio button problematically, you need to re-style it using .checkboxradio("refresh").

To bind event, use pageinit as it fires once per page, this will ensure you dont add multiple listeners to the same item.

Since all checkboxes has the same .fruits, check if the checked one has hatefruit id. Accordingly, check/uncheck the rest of checkboxes.

$(document).on("pageinit", "#page1", function () {
    $(".fruits").on("change", function () {
        if ($(this).is(":checked") && this.id == "hatefruit") {
            $('.fruits').prop('checked', false).checkboxradio("refresh");
            $(this).prop('checked', true).checkboxradio("refresh");
        } else {
            $('#hatefruit').prop('checked', false).checkboxradio("refresh");
        }
    });
});

Demo

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top