This might be a question which has already been asked, but I couldn't find the right answer for it. So I'm asking it just to be sure.
Now, I know jQuery provides an attribute selector such as :checked to get all the checked checkboxes, but you would need to include this in the selector itself.
But is there a way to do this seperately from the selector? What I mean is, what if you store your selector in a variable?
Example
var checkboxSelector = $("input[name='myCheckboxes']");
So this would have a general use in the overall code, so I wouldn't have to write the selector each time I need it. But what if I wanted to get the total amount of checked checkboxes with the name-attribute myCheckboxes?
The obvious way would be $("input[name='myCheckboxes']:checked").length, but since I'm using my variable checkboxSelector I cannot include the :checked-selector.
The way I know to get the total amount would be to use an .each() on my selector and use a counter to get the total amount, but I was wondering if there was an easier way to achieve this?
so instead of doing this:
var checkboxSelector = $("input[name='myCheckboxes']");
/* Do some stuff with the variable*/
/* Time to get the total amount of checked checkboxes */
var count = 0;
checkboxSelector.each(function() {
if($(this).is(":checked"))
count++;
});
I was hoping there would be a way to do it like this (or something similar)
var count = checkboxSelector.is(":checked").length;
Now I know this wouldn't give me the total amount, but it is just an example. Is there any way to give me the count of all checked checkboxes by storing my selector in a variable? Preferably by not using an .each() to get the count.
Thanks in advance!
EDIT
Just to be clear, I cannot use the following selector:
var count = $("input[name='myCheckboxes']:checked").length;
since my selector is stored in a variable, I would have to use it like this:
var checkboxSelector = $("input[name='myCheckboxes']");
/* At this point I cannot include the :checked attribute anymore */
So $("input[name='myCheckboxes']:checked") is not an option.
Aucun commentaire:
Enregistrer un commentaire