如果选中另一个元素,则取消选中jQuery Mobile

时间:2014-02-03 17:10:55

标签: jquery jquery-mobile checked

我在这里找不到错误。

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

我只是想这样做:

情景1:
     - 用户检查一堆复选框      - 用户检查“我讨厌水果”
     - 所有其他复选框均未经检查,“I Hate Fruit”除外

情景2:
     - 用户已经检查了“我讨厌水果”      - 用户点击任何其他复选框      - 自动取消选中“我讨厌水果”复选框。

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);
    }
  });

});

1 个答案:

答案 0 :(得分:3)

首先,您不应在jQuery Mobile中使用.ready()。其次,当您选中/取消选中复选框或单选按钮时,需要使用.checkboxradio("refresh")重新设置样式。

要绑定事件,请在每页触发一次时使用pageinit,这样可确保您不会将多个侦听器添加到同一项目中。

由于所有复选框都具有相同的.fruits,因此请检查已选中是否具有 hatefruit ID。因此,选中/取消选中其余复选框。

$(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