1

I have some checkboxes in a form. When they are checked, a hidden field is added to the form.

A couple of the checkboxes are checked initially, and I don't want to modify the HTML to include the related hidden fields. Instead, I want to be able to trigger the same code to add the hidden fields automatically when the page loads initially.

I have tried something like this, but with no luck:

container.find("input[data-subscribe]").on("change load", function()
// ------------------------------------------------^^^^ Thought adding load here
//                                                      might do what I want.
{
    var lists = $(this).data("subscribe").toString();
    lists = lists.split(";");

    for(var i = 0; i < lists.length; i++)
    {
        var list = lists[i];

        if($(this).is(":checked")) container.prepend('<input type="hidden" name="lists" value="' + list + '">');
        else container.find("input[type=hidden][value=" + list + "]").remove();
    }

});

Of course I could just copy the code and put it in a $(document).ready() handler, but if there's just an event I can add to the above on, that would be much cleaner.

4

2 回答 2

1

在 dom 就绪时触发更改事件

container.find("input[data-subscribe]").change()

或者

container.find("input[data-subscribe]").trigger('change')
于 2013-06-24T03:12:45.110 回答
0

将它包装在一个函数中并从两个处理程序中调用它:

function someCheckboxfunction(lists) {
    lists = lists.split(";");

    for(var i = 0; i < lists.length; i++)
    {
        var list = lists[i];

        if($(this).is(":checked")) {
            container.prepend('<input type="hidden" name="lists" value="' + list + '">');
        }
        else {
            container.find("input[type=hidden][value=" + list + "]").remove();
        }
    }
}

调用代码

$(document).ready(function() {        
    container.find(("input[data-subscribe]").on("change", function() { 
        someCheckboxFunction($(this).data("subscribe").toString()) 
    });

    var lists = container.find("input[data-subscribe]").data("subscribe").toString();
    someCheckboxFunction(lists);
});
于 2013-06-24T02:57:59.470 回答