why does my checkbox always get unchecked?

泪湿孤枕 提交于 2021-01-27 17:43:01

问题


The following code adds a checkbox and a label to the calling node.
My question lies in the label.click function. Whenever the label is clicked I want to change the state of the matching checkbox. What happens however is that the checkbox always ends up unchecked. For debugging purposes I now always explicitly set it to checked.

When I step through the code with firebug I see that the checkbox gets checked and then, when leaving the function it gets unchecked again.

Any ideas?

jQuery.fn.AddEndOrStartWith = function(selected, id, action) {
    var checkBox = $('<input type="checkbox"></input>');
    checkBox.attr("id", id + action);
    checkBox.addClass(action + "CheckBox");
    checkBox.attr("for", id);

    var label = $('<label></label>');
    label.attr("for", id + action);

    if (selected) {
        checkBox.attr("checked", "checked");
        label.addClass("lockerClosed");
    } else {
        label.addClass("lockerOpen");
    }

    $(this).append(label);
    $(this).append(checkBox);

    label.click(function() {
        /*alert(checkBox.attr("checked"));*/
        checkBox.attr("checked", "checked");
        /*return true;*/
        /*alert(checkBox.attr("checked"));*/
    });
}

回答1:


You need to prevent the default action in your label click handler. Think this should do it:

label.click(function() {
     checkBox.attr("checked", "checked");
     return false;
});

What's going on is that because your label is set up with its for referring to the checkbox correctly, the default action when clicking on it is to toggle the checkbox.

Though, um, if that's all you're trying to do with your click handler, I guess you could just not even use a click handler. But I'm not sure whether that's the case.




回答2:


After two afternoons of searching I put it on SO and then within a few minutes I found it myself..

Apparently when setting the id of the checkbox, setting the for attribute on the label and then returning positive on the click function somehow makes it false. By making the click function return false, I break the cycle without invalidating my HTML.

Final code:

jQuery.fn.AddEndOrStartWith = function(selected, id, action) {
    var checkBox = $('<input type="checkbox"></input>');
    checkBox.attr("id", id + action);
    checkBox.addClass(action + "CheckBox");

    var label = $('<label></label>');
    label.attr("for", id + action);

    if (selected) {
        checkBox.attr("checked", "checked");
        label.addClass("lockerClosed");
    } else {
        label.addClass("lockerOpen");
    }

    $(this).append(label);
    $(this).append(checkBox);

    label.click(function() {
        checkBox.attr("checked", !checkBox.attr("checked"));
        return false;
    });
}


来源:https://stackoverflow.com/questions/1137062/why-does-my-checkbox-always-get-unchecked

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