Alejandro B.
Alejandro B.

Reputation: 5092

jQuery to get elements whose id end with any of many constants

I need a jQuery to get all checked checkboxes whose ID ends with PR, PR_KD or PR_KDA. I have tried this with no luck:

jQuery("#" + panelInfo[0] + "_row_" + panelInfo[1] + " input:checked").find(":[id$=_chkPR], :[id$=_chkPR_KD], :[id$=_chkPR_KDA])");

and also this:

jQuery("#" + panelInfo[0] + "_row_" + panelInfo[1] + " input:checked:[id$=_chkPR, id$=_chkPR_KD, id$=_chkPR_KDA]")

I fail to use the "or" correctly. Can anyone help me?

Thanks in advance!

Alejandro.

Upvotes: 4

Views: 1360

Answers (3)

David Hedlund
David Hedlund

Reputation: 129792

Your first example query is the closest one to a proper syntax, but you're using $('... input:checked').find() which will look for children of those checkboxes (of which of course there will be none).

So you need to move the input:checked part, or better yet :checkbox:checked, to exclude any radiobuttons, into your .find, so that you're searching within the desired container, rather than within the list of checkboxes:

jQuery("#" + panelInfo[0] + "_row_" + panelInfo[1])
    .find(":checkbox:checked[id$=_chkPR], :checkbox:checked[id$=_chkPR_KD], :checkbox:checked[id$=_chkPR_KDA])");

Another way of expressing it might be:

jQuery("#" + panelInfo[0] + "_row_" + panelInfo[1])
   .find('[id$=_chkPR], [id$=_chkPR_KD], [$=id_chkPR_KDA]')
   .filter(function() { return $(this).is(':checkbox:checked'); });

In the above code, you're finding all elements in the panel with a matching ID, and filtering out the elements, out of the matching set, that are checked checkboxes.

You could also get rid of the need of using .find at all, if you instead supply a context:

jQuery(":checkbox:checked[id$=_chkPR], :checkbox:checked[id$=_chkPR_KD], :checkbox:checked[id$=_chkPR_KDA])",
    document.getElementById(panelInfo[0] + "_row_" + panelInfo[1]));

Upvotes: 2

James Hill
James Hill

Reputation: 61812

You're very close. Change your find() to this:

.find(":checkbox:checked[id$=_chkPR], :checkbox:checked[id$=_chkPR_KD], :checkbox:checked[id$=_chkPR_KDA]")

Final code:

jQuery("#" + panelInfo[0] + "_row_" + panelInfo[1]).find(":checkbox:checked[id$=_chkPR], :checkbox:checked[id$=_chkPR_KD], :checkbox:checked[id$=_chkPR_KDA]")

Here's a working fiddle.

Upvotes: 3

Ryan Brodie
Ryan Brodie

Reputation: 6620

This should help:

http://forum.jquery.com/topic/count-checked-checkboxes

Upvotes: 0

Related Questions