Pierre
Pierre

Reputation: 5156

jquery - select all checkboxes with js array name

I want to use a JQuery "check all" function in a form like this: http://jetlogs.org/jquery/jquery_select_all.html

My problem is I am generating my form from a php script, and I don't know exactly how many checkboxes I will have in advance. I use the "array" naming convention to be able to get all the selected checkbox values in my $_POST data... so my checkboxes are like that:

<input type="checkbox" name="items[]" value="<?php echo $id ?>">

but this JQuery declaration does not work:

$("input[@name=items[]]").each(function()    
{    
    this.checked = checked_status;    
});

probably because the "[]" at the end of my "items" messes up the JQuery declaration... I tried to write @name=items[] like that: "@name=items[]", and to put some anti-slash before the [ and ] so they're not considered as special characters but it didnt work...

If someone knows a solution and is willing to share it'd be great!! :)

Upvotes: 27

Views: 54919

Answers (4)

Piotr Rochala
Piotr Rochala

Reputation: 7781

Escape internal brackets with \\(no space) - it should fix the problem.

This selector works for me:

$('input[name=items\\[\\]]')

Upvotes: 63

Kannan Prasad
Kannan Prasad

Reputation: 1806

$("input[name='smsid[]']")

This code works fine for me...

Upvotes: 2

Kennethvr
Kennethvr

Reputation: 2690

First of all, your name attribute should be used to set +1 elements with the same name. It's practically the same as the id attribute and should be unique per element excepted for references, but that is not the case for you.

Try using the class attribute, it's made for the things you want to do!

another thing is that in your code, you can only set your checkboxes to 'checked', but never to uncheck, this code will set your checkboxes to checked true or false, according to what it gets as attribute from the clicked element.

you can do something like this:

set your check all checkbox with an id

 <input type="checkbox" id="checkAll">

Then set on all checkboxes that should be checked/unchecked a class

<input type="checkbox" class="checked">

And the you can do something like this in jQuery

$("#checkAll").click( function(){
 var checkedValue = $(this).attr("checked");
 $("input.checked").attr("checked", checkedValue); });

this will change all checkboxes with class checked to the same checked attribute as the one with id checkAll

Upvotes: 4

Emil Ivanov
Emil Ivanov

Reputation: 37673

Try using

$('input[name="items[]"]')

No need for @ and use ". Note that the selector outside quotes are '. Otherwise you might cause parse error.

Upvotes: 15

Related Questions