Domanda

Fiddle http://jsfiddle.net/hdD8B/

I'm having trouble replacing this code that worked in jQuery 1.7.

I have a button that simply checks all the checkboxes when clicked and then unchecks them when clicked again.

    $('.check:button').toggle(
        function () {
        $('input:checkbox').attr('checked', 'checked');
        $(this).val('uncheck all');
    }, function () {
        $('input:checkbox').removeAttr('checked');
        $(this).val('check all');
    });

this is the closest I have been able to get it works to check and uncheck all once then doesn't work anymore. It also seems kind of ugly to have to a simple method replaced with a more complicated on.

(function ($) {
    $.fn.clickToggle = function (func1, func2) {
        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function () {
            var data = $(this).data();
            var tc = data.toggleclicked;
            $.proxy(funcs[tc], this)();
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };
}(jQuery));

/*global $, jQuery,document,fnCreateSelect*/
$(document).ready(function () {





    $('.check:button').clickToggle(
        function () {
        $('input:checkbox').attr('checked', 'checked');
        $(this).val('uncheck all');
    }, function () {
        $('input:checkbox').removeAttr('checked');
        $(this).val('check all');
    });
È stato utile?

Soluzione

As you may have read, .toggle() was removed after jQuery 1.8 -

Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed. http://api.jquery.com/toggle-event/

Here is one way to fix the issue -

$('.check:button').click(function () {
    if('check all' == $(this).val() ) {
        $('input:checkbox').prop('checked', true);
        $(this).val('uncheck all');
    } else {
        $('input:checkbox').prop('checked', false);
        $(this).val('check all');
    }
});

You'll notice that I switched to prop() instead of attr() as prop() is considered en vogue for elements like this. There has been much debate on "best practices" though but this post makes good reading - .prop() vs .attr()

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top