Arianule
Arianule

Reputation: 9063

selecting all checkboxes in jquery

I want to select all checkboxes of a specific name by checking a single checkbox on a page and trigger the subsequent events.

As I have it at the moment it doesnt seem to fire immediately, so upon the first checking of the 'select all' checkbox the checkboxes are not selected and then by unchecking the 'select all' check box all the checkboxes are checked.

Seems a bit upside down.

How can I improve the following code so that it works properly?

$(document).on("click", "input[name='chkAllBs']", function () {

if ($('input[name = chkBestSeller]').prop('checked') == false) {
    $('input[name=chkBestSeller]').attr("checked", "true");
    $('input[name=chkBestSeller]').trigger('click');
}
else {
    $('input[name=chkBestSeller]').attr("checked", "false");
    $('input[name=chkBestSeller]').trigger('click');
}

Upvotes: 0

Views: 86

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388436

Try

$(document).on("click", "input[name='chkAllBs']", function () {
    $('input[name=chkBestSeller]').prop("checked", this.checked);
});

Upvotes: 3

Dipesh Parmar
Dipesh Parmar

Reputation: 27382

$(document).on("click", "input[name='chkAllBs']", function () {
    var c = this.checked;
    $('input[name = chkBestSeller]').prop('checked',c);
});

Upvotes: 1

GautamD31
GautamD31

Reputation: 28763

It will be like

if ($('input[name = chkBestSeller]').prop('checked') == true) {

    $('input[name=chkBestSeller]').attr("checked", true);
} else {

    $('input[name=chkBestSeller]').attr("checked", false);
}

Or simply

$(document).on("click", "input[name='chkAllBs']", function () {
    $('input[name="chkBestSeller"]').prop("checked", this.checked);
});

Upvotes: 1

Related Questions