jquery输入复选框checkall或some

时间:2012-01-23 10:34:13

标签: jquery checkbox toggle

两个选项 单击复选框1然后显示并选择2 点击第2段然后显示abcde

选项1工作正常

我在选项2上出错了

我希望选择abcd和e

之一

这是jquery

$(document).ready(function() {
    $('.child').hide();
    $(".parent").click(function() {
        $('#form' + $(this).attr('id')).toggle();
        $(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
    });

});

这是html

    <fieldset>
        <p>
            <label for="5">1</label>
            <input type="checkbox" name="1" id="5" value="360" class="parent" />$360
        </p>
        <p id="form5" class="child">
            <label for="6">2</label>
            <input type="checkbox" name="2" id="6" value="2" />$180
        </p>
    </fieldset>
<fieldset>
<p name="4" id="1st" class="parent">a</p>
<p id="form1st" class="child">
        <label for="7">a</label>
        <input type="checkbox" name="a" id="7" value="25"  />$25
<br />
        <label for="8">b</label>
        <input type="checkbox" name="b" id="8" value="18"  />$18
<br />
        <label for="9">c</label>
        <input type="checkbox" name="c" id="9" value="18"  />$18
<br />
        <label for="10">d</label>
        <input type="checkbox" name="d" id="10" value="18"  />$18
<br />
        <label for="11">e</label>
        <span id="11">
                <input type="checkbox" name="?" value="18"  />e1
                <input type="checkbox" name="?" value="36"  />e2
                <input type="checkbox" name="?" value="54"  />e3
                <input type="checkbox" name="?" value="72"  />e4
                <input type="checkbox" name="?" value="90"  />e5
                <input type="checkbox" name="?" value="100"  />e6
                <input type="checkbox" name="?" value=""  />other
        </span>
    </p>
</fieldset>

和演示

http://jsfiddle.net/vRXU3/

2 个答案:

答案 0 :(得分:2)

这是你的问题。

“选项2”

中未定义

this.checked

.attr('checked', this.checked)

单击

时有效
 <input type="checkbox" name="1" id="5" value="360" class="parent" />

因为它是一个复选框,并且具有cheched属性。但是当你点击

<p name="4" id="1st" class="parent">a</p>

使用'this',您可以引用没有<p>属性的checked元素

- 更新

$(".parent").click(function() {

    var $target = $(event.target);
    var valueOfChecked;
    if ($target.is("input:checkbox")) {
        valueOfChecked = $target.attr('checked');
    } else {
        valueOfChecked = 'checked';
    }
    $(this).parents('fieldset:eq(0)').find('p > input:checkbox').attr('checked', valueOfChecked);
    $(this).parents('fieldset:eq(0)').find('p > span input:checkbox').first().attr('checked', valueOfChecked);
});

jsfiddle updated example

答案 1 :(得分:0)

我会要求您将脚本更改为:

$(document).ready(function() {
    $('.child').hide();
    $(".parent").click(function() {
        $('#form' + $(this).attr('id')).toggle();
        $(this).parents().find('input:checkbox').attr('checked', this.checked);
    });

});

已更新$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);

已删除'fieldset:eq(0)'这不是必需的。

相关问题