views:

837

answers:

4

This is probably a really simple jQuery question, but I couldn't answer it after 10 minutes in the documentation so...

I have a list of checkboxes, and I can get them with the selector 'input[type=checkbox]'. I want the user to be able to shift-click and select a range of checkboxes. To accomplish this, I need to get the index of a checkbox in the list, so I can pass that index to .slice(start, end). How do I get the index when the user clicks a box?

+4  A: 

The following selector should also work in jQuery: 'input:checkbox'.

You can then string the :gt(index) and :lt(index) filters together, so if you want the 5th to 7th checkboxes, you'd use 'input:checkbox:gt(4):lt(2)'.

To get the index of the currently clicked checkbox, just use $("input:checkbox").index($(this)).

samjudson
A: 

This is a quick solution, but I would give each checkbox a unique ID, perhaps with an index hint, like so:

    <input id="checkbox-0" type="checkbox" />
    <input id="checkbox-1" type="checkbox" />
    <input id="checkbox-2" type="checkbox" />
    <input id="checkbox-3" type="checkbox" />
    <input id="checkbox-4" type="checkbox" />

You can then easily obtain the index:

        $(document).ready(function() {
            $("input:checkbox").click(function() {
                index = /checkbox-(\d+)/.exec(this.id)[1];
                alert(index);
            });
        });
Ryan Duffield
A: 

Thanks for the answer, samjudson.

After further experimentation, I found that you can even use just $(':checkbox') to select them. It's interesting that you can use the .slice() function to get the range, but you also have the option of doing it in the selector with :gt and :lt. I do find the syntax of .slice() to be cleaner than using the selector filters, though.

I'm going to have to say that I don't like Ryan Duffield's solution as much, because it requires changes to the markup, and involves repeating code.

Christian Oudard
A: 

@Gorgapor: I guess I need to take questions a little less literally sometimes. :-) I figured you were locked down to requiring some sort of index. I think you'll find though that as you use jQuery more, you usually don't need to do that sort of thing.

Ryan Duffield