views:

50

answers:

1

Ok, so I wrote this function to be a change event applied to a checkbox. Now it is apparent I need to use it as a custom validator method, so it runs when you hit "Next" to step through the form. I have all that working, I just can't get the syntax of the rule right.

Here it is as a change event:

$('#MKDPT').change(function() {
if ($('#MKDPT').is(':checked')) { 
    var checked = false;
    var ckd = ['AMX1N','BMFNP','BMFNB','CFE1N','CBEXR','CBT1','CBTQL','CME1','CMEQL','CMX1','DCMX1','DMERT','DMEDL','ERX1N','ERXXN','EXC1N','EXD1N','EXR1N','EXI1N','IPE1','KCB1','LME1','DLME1','MPL1','NDQ1N','NDQL2','CEC1','ICEFI','NYM1','DNYM1','NYMQL','NYS1N','NYSLM','PNK1P','PNK2N','SMX1','CNC1N','CNS1N','MTL1N','MTL2N','WEA1'];
    $('#' + ckd.join(',#')).each(function() { // Select all these IDs
        if (this.checked) { // Is this one checked?
            checked = true;
        }
        return !checked; // Exit if any are checked 
    });
    if (!checked) { // None are checked
        MKDPTAlert1(); 
    }
}      
});

And my attempt at a custom validation rule:

$.validator.addMethod(
    "MKDPTOnly",
    function(value, element, params) {
    var checked = false;
    var ckd = ['AMX1N','BMFNP','BMFNB','CFE1N','CBEXR','CBT1','CBTQL','CME1','CMEQL','CMX1','DCMX1','DMERT','DMEDL','ERX1N','ERXXN','EXC1N','EXD1N','EXR1N','EXI1N','IPE1','KCB1','LME1','DLME1','MPL1','NDQ1N','NDQL2','CEC1','ICEFI','NYM1','DNYM1','NYMQL','NYS1N','NYSLM','PNK1P','PNK2N','SMX1','CNC1N','CNS1N','MTL1N','MTL2N','WEA1'];$('#' + ckd.join(',#')).each(function() { // Select all these IDs
        if (this.checked) { // Is this one checked?
            checked = true;
        }
        return !checked; // Exit if any are checked 
    });
    if (!checked) { // None are checked

    }
}, Alert("foo");
);

As you can see, it is broken. I would like this to display as an alert, not the standard error placement. Do I need to use the var "ckd" as a param? Im not really entirely clear on how those work but have used them before with a lot of help.

Thanks!

A: 

Here's an alternative method that ought to do the trick:

$('#myForm').validate({
  rules:{
     MKDPT: {
       required: {
         depends: function(element){
           return $('.others:checked').length;
         }
       }
     }
  },
  messages:{
    MKDPT: 'foo'
  }
});

Note that this assumes you've assigned your collection of other checkboxes the class others.

Ryley
So I don't need to do any of the steps with addMethod? simply add the class to the other checkboxes and use "depends:...." on the rule? Seems to good to be true!
Dirty Bird Design
Should be that simple yeah!
Ryley
@Ryley - Didn't seem to do anything. is the return based on the length > 0? If I had no boxes with the class "others" checked and MKDPT checked it should return the error.
Dirty Bird Design