Html checkBox onchange 不起作用

问题描述 投票:0回答:4
<input class="jProblemClass" id="Checkbox{%= ID %}" type="checkbox" onchange="problemPicker.onChangeProblemCheckBox('{%=ID %}');"/>

首次选中或取消选中后,没有任何反应。第二次点击后,调用我的函数

problemPicker.onChangeProblemCheckBox
,但我首先检查ID。为什么?有人可以帮助我吗?

onChangeProblemCheckBox: function(id) {
    if ($('#CheckBox' + id).attr("checked") == true) {
        problemPicker.addToCheckProblems(id);

        var checkboxes = $('.jProblemClass:checked');

        if ((checkboxes.length > general.limit) && (general.limit != 0)) {
            alert('The limit of ' + general.limit + ' problems exceeded. Please deselect ' + (checkboxes.length - general.limit).toString() + '.');
        }
    } else {
        problemPicker.delFromCheckProblems(id);
    }
},
jquery html checkbox onchange
4个回答
25
投票

兄弟使用onclick事件而不是onchange.. 原因... 根据我读过的 Javascript 参考资料, onchange 在 失去焦点。除非您点击其他地方,否则焦点不会在 IE 中丢失。 其他浏览器一定不能等待焦点丢失之前 触发 onchange - 这表明他们没有正确遵循规范 (尽管此时开火更有意义)。怎么样使用 onclick 和 onkeydown/onkeyup 代替(通过同时使用 onclick 和 onkeyup/onkeydown 您涵盖了鼠标和键盘设置 复选框)。 参考:http://www.winvistatips.com/re-onchange-event-checkbox-not-working-properly-t311364.html


1
投票

我想,问题出自这里:

$('#CheckBox' + id).attr("checked") == true
。根据 HTML 规范,当此事件触发时,
checked
应设置为
"checked"
。因此,请尝试使用类似
$('#CheckBox' + id).attr("checked") == "checked"
甚至
$('#CheckBox' + id).attr("checked")
的内容。

作为第二个选项,我建议您使用纯 jquery 来运行您的例程。例如,如果您有

<input type="checkbox" id="ac">
复选框,则可以使用此 jq 代码来处理您的例程:

$(document).ready(function() {
    $("input[type=checkbox]").change(function() {
        alert("Am i checked? - " + $(this).attr("checked") + "\nMy ID:" + $(this).attr("id"));
    });
});

此案例显示在此演示中。


0
投票

尝试使用

if($('#CheckBox' + id + ':checked').length > 0)
来代替,这样你就可以让 jQuery 判断出该复选框是否被 checked

此外,如果

onChangeProblemCheckBox
使用
problemPicker
中的任何内部属性,但未使用完整路径引用它们,即
problemPicker.nnnnn
它将失败,因为事件将在元素的上下文中触发,而不是 ProblemPicker。就好像这个函数是这样调用的
$('#CheckBox' + id).onChangeProblemCheckBox()
.


0
投票

非常简单:使用 onClick 代替并使用 defaultChecked 来填充输入。

© www.soinside.com 2019 - 2024. All rights reserved.