Question

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');
Was it helpful?

Solution

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');

OTHER TIPS

Thanks it worked. Instead of is(':checked') I used .prop('checked'),

        var lastCheckBox = $('[name="LastCheckboxId"]:last');

        //onload
        $(".someDiv").hide();
        if (lastCheckBox .prop('checked')) {
            $(".someDiv").show();
        }

        //onchange
        lastCheckBox.change(function () {
            if ($(this).prop('checked')) {
                $(".someDiv").show();
            } else {
                $(".someDiv").hide();
            }
        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top