views:

29

answers:

1

I'm trying to setup custom validation for a checkbox. I have 7 checkboxes each with the same name and I want to identify if the last one is checked. This is the code I have and I know its wrong, could anyone shed some light on how to properly stack the :last and :checked selectors together?

$.validator.addMethod('ObserverOtherBox',function(v, e) {
   return ($('[[name="4_observers"]:last]:checked').length == 1) && ($('[name="4_observerstxt"]').length == 0) ;
}, 'Please enter the other observers');
+3  A: 

You stack selectors like this:

$('[name="4_observers"]:last:checked')

Just append them together, no spaces, this works for all selectors, whether it's:

$('[name="4_observers"][id=4][rel=bob]')
// or:
$(':input:checkbox:last:checked')

Or course those are terrible actual selectors, but you get the point :)

Also as an aside, you can write your particular code like this, a bit clearer I think:

$.validator.addMethod('ObserverOtherBox',function(v, e) {
  return $('[name="4_observers"]:last').is(':checked') 
      && $('[name="4_observerstxt"]').length == 0;
}, 'Please enter the other observers');
Nick Craver
Wouldn't that get "the last checkbox, if it is checked" and not "the last checkbox that is checked"?
Tomalak
@Tomalak - Yes it would, the question is asking for this though: "I want to identify if the last one is checked". To get the last checked one, you would do `$('[name="4_observers"]:checked').last()`...but unless I misunderstood, this isn't what the question's asking. I think his last checkbox is "other", and if it's checked, another field is required (the other textbox maybe?)
Nick Craver
Ahh I see it now, I misread the question. Still, my own try just now has left me puzzled: I applied `$("input[name=author]:last")` and `$("input:last[name=author]")` to this very StackOverflow page. They both return the same, but they should not (as `input[name=author]` is not the last input on the page). What gives?
Tomalak
@Tomalak - I believe, don't quote me, that attribute selectors are always applied before pseudo-class selectors, will try and find documentation to that effect, but I think that's always true.
Nick Craver
Hm… I suspect something similar. I really thought jQuery selectors would be evaluated strictly from left to right.
Tomalak
@Nick is correct... Want to see if the last checkbox with that name is checked (there are several with the same name). Then if that is true, make the other text field required. Problem is that last bit of code you provided triggers the validation error no matter what (box checked, unchecked, text box empty or typed in). So something must be amiss with it but I can't figure out what.
jethomas