2

我正在使用 jquery Tools 验证器插件,并且我有一个包含多个部分的表单。每个部分的顶部都有一个复选框,我希望它像每个部分的主开关 - 以编程方式打开/关闭每个部分中文本框和电子邮件字段的功能(如验证)。

基本上,如果选择了相应的组复选框,我想有条件地将“文本”和/或“电子邮件”类型输入字段的属性设置为“必需”。不可否认,我对 jQuery 不是很好。

每个表单部分与下面类似,但可能有不同数量的文本和/或电子邮件字段:

<input type="checkbox" group-name="mail" name="mail" id="mail_enable"
       checked="<?= (chkConfig("mail_enable", 0) ? "yes" :  "no"); ?>"
       onChange="chkRequired('mail');"   
       title='check this box to send the specified reports to your email.' > 
       <label for="mail_enable">notify me when the batch is complete.</label></div>
  <div class="left"><label for="lblemailid">Email Address: </label></div>
  <div class="right"><input type="email" group-name="mail" name="mailto" 
       id="emailAddress" size="30" maxlength="50" />

我创建了一个名为 group-name 的属性,并且一个部分中的所有字段共享相同的 group-name。在 Frédéric Hamidi 先生的帮助下(在我们下面的讨论中),我们修改了我的功能。这是最新版本:

  function chkRequired(group){ 
    var groupCheckBox = $("#" + group + "_enable");
    var groupSelector = "[group-name='" + groupCheckBox.attr("group-name") + "']";
    var fieldSelector = "input[type=text], input[type=email]";
     if  ( $(groupCheckBox).is(':checked'))  {
        $(groupSelector).add(fieldSelector).attr("required");
       } else { 
        $(groupSelector).add(fieldSelector).removeAttr("required");
     }
   }

我希望这对处于类似情况的其他人有所帮助。

我仍然无法弄清楚将其附加到 doc.ready() amd .change() 全局的选择器语法。但如果您手动将函数分配给字段的 onChange 事件,它会起作用。

此外,如果有人可以帮助我了解 validator.addMethod() 的语法,那么我们就可以创建一个自定义验证方法 - 那将不胜感激。

特别感谢 Frédéric Hamidi 先生帮助我找出逻辑。

如果有人感兴趣,我创建了一个更详细的教程@ http://www.logicwizards.net/2010/12/07/jquery-tools-custom-validator-mod/

Joe Negron:逻辑奇才~纽约

4

1 回答 1

3

Well, $('#'+groupName).val() returns undefined because your check box matches #mail_enable, not #mail. You don't even need to compute it a second time, since you used it the line before to get at the group name.

Also, val() returns the value of the check box, not its check state. You need the checked attribute (or the :checked selector) for that:

function chkRequired(group)
{
    var groupCheckBox = $("#" + group + "_enable");
    var groupSelector = "[group-name='" + groupCheckBox.attr("group-name") + "']";
    if (groupCheckBox.is(":checked")) {
        $("input:text" + groupSelector).attr("required", "required");
        $("input[type='mail']" + groupSelector).attr("required", "required");
    } else { 
        $("input:text" + groupSelector).removeAttr("required");
        $("input[type='mail']" + groupSelector).removeAttr("required");
    }
}
于 2010-12-06T20:22:52.597 回答