Html checkBox onchange not working

旧城冷巷雨未停 提交于 2019-12-12 08:47:38

问题


<input class="jProblemClass" id="Checkbox{%= ID %}" type="checkbox" onchange="problemPicker.onChangeProblemCheckBox('{%=ID %}');"/>

After first check or uncheck nothing happens. Afetr second click, call my function problemPicker.onChangeProblemCheckBox, but i get ID first check. Why? Can help me anybody?

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

回答1:


Bro use onclick event instead onchange.. Reason... According to the Javascript references I've read, onchange fires after the focus is lost. Unless you click somewhere else, the focus is not lost in IE. The other browsers must not be waiting for the focus to be lost before firing onchange - which suggest they are not following the spec correctly (despite it making more sense to fire at that point). How about using onclick and onkeydown/onkeyup instead (by using both onclick and onkeyup/onkeydown you cover both mouse and keyboard setting of the checkbox). REFERENCE : http://www.winvistatips.com/re-onchange-event-checkbox-not-working-properly-t311364.html




回答2:


I think, the problem goes from here: $('#CheckBox' + id).attr("checked") == true. Accordingly to HTML specs, checked should be set to "checked" when this event fires. So, try using something like $('#CheckBox' + id).attr("checked") == "checked" or even $('#CheckBox' + id).attr("checked").

As a second option, i recommend you to use pure jquery to run your routine. For example, if you have <input type="checkbox" id="ac"> checkbox, you can use this jq code to handle your routines:

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

This case is shown in this demo.




回答3:


Try using if($('#CheckBox' + id + ':checked').length > 0) instead, that way you led jQuery figure out it the checkbox is checked or not.

Also if the onChangeProblemCheckBox uses any internal properties in problemPicker but does not referens them with full path, ie problemPicker.nnnnnit will fail as the event will fire in the context of the element, not problemPicker. It would be as if the function was called like this $('#CheckBox' + id).onChangeProblemCheckBox().



来源:https://stackoverflow.com/questions/4942437/html-checkbox-onchange-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!