Marty
Marty

Reputation: 39456

Do something with checkbox both initially and on change using jQuery

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.

Upvotes: 1

Views: 69

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

On dom ready just trigger the change event

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

Or

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

Upvotes: 1

James Hay
James Hay

Reputation: 7315

Wrap it in a function and call it from both handlers:

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

Calling code

$(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);
});

Upvotes: 0

Related Questions