开发者

Stacking :last and :checked jQuery selectors together

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


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


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();
            }
        });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜