开发者

jquery validate: adding a required rule with custom message based on wether a different form field has a value

开发者 https://www.devze.com 2022-12-21 13:26 出处:网络
I know this seems like a repeat question, but i\'v开发者_开发问答e read all the others and they arn\'t quite the same :(

I know this seems like a repeat question, but i'v开发者_开发问答e read all the others and they arn't quite the same :(

I've got some drop downs, and if they have something other then an option with a value of "0" selected then I want the coresponding Expiry Date field to be required.

I tried putting the rule in the class of the objects, and using the rules('add') function. Here's where i am at right now:

$('[id^=ExpiryDate]').each(function() {

    $(this).rules('add',
    { required: function() {
        if ($('#q' + id).val() == '0') {
            return false;
        }
        else {
            return true;
        }
    } 
    }
);

my expiry date fields are id'ed like "ExpiryDate1", "ExpiryDate2" and the corresponding drop downs are ided like "q1" and "q2".

this makes my scripts fail. it doesn't give any errors in the error console or firebug. but it doesn't execute any javascript that occurs after it either.

I have a feeling it's something really obvious and stupid that i am missing. but i've been staring at this code for a couple hours now and can't find it!

Thanks in advance!


Try this:

$('[id^=ExpiryDate]').each(function() {
  var id = $(this).attr('id').replace('ExpiryDate','');
  $(this).rules('add', { 
    required: function() {
      return $('#q' + id).val() !== '0';
    } 
  }
);

Currently, your id is undefined, so it's just not finding any elements. The rest is just a shorter version.

0

精彩评论

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