Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select and Unselect a group of Checkboxes with jQuery

let's start from the beginning, but please don't panic... is a Jquery issue ;-)

I writing a PHP code: the user sends a query to our database and the form shows sets of results, grouped in tables, with checkboxes to select the data.

I would like to know how to enable a Jquery code to run with a Select/Deselect checkbox, to Select/Deselect the data of each table, i mean, each set of results.

For example, something like this example http://www.wiseguysonly.com/2010/01/15/select-and-unselect-all-checkboxes-with-jquery/

1: All checkboxes have a class of “checkbox”: input type=”checkbox” class=”checkbox”

function toggleChecked(status) {
    $(".checkbox").each( function() {
        $(this).attr("checked",status);
    });
}

Could you tell me what is the best way to modify the toggleChecked function?

A second parameter to call toggleChecked, to replace ".checkbox" with the second parameter value? (i'm unable to find the correct syntax to do it).

Or there is a different way to do it?

And, BTW, is better to use prop instead attr? Best regards.

like image 405
David García Aristegui Avatar asked Nov 28 '25 22:11

David García Aristegui


1 Answers

Just add a second parameter to the function, and use it.

function toggleChecked(status,selector) {
    $(selector).each(......);
}

If you are honestly struggling with something as simple as this, you really shouldn't be using jQuery yet. You should learn about plain JavaScript first. Otherwise it's like going to a construction site with the best tools in the world, maybe even the knowledge of how to use those tools perfectly... but with no idea how basic construction works, you'd probably make a beautiful building with no foundations that would collapse within a day.

like image 117
Niet the Dark Absol Avatar answered Dec 01 '25 12:12

Niet the Dark Absol