【问题标题】:jquery validate: dyanamically generated checkboxes (with not the same name)jquery validate:动态生成的复选框(名称不同)
【发布时间】:2013-12-18 09:02:51
【问题描述】:

我在typo3 中使用的是旧版本的powermail 扩展程序。 这个分机。创建以下标记:

<input type="checkbox" id="uid53_0" value="1" name="tx_powermail_pi1[uid53][0]">
<input type="checkbox" id="uid53_1" value="2" name="tx_powermail_pi1[uid53][1]">
<input type="checkbox" id="uid53_2" value="3" name="tx_powermail_pi1[uid53][2]">

所以名字并不完全相同。

我试过这个 sn-p 来验证:

$('#formid').validate({
    rules: {
        'tx_powermail_pi1[uid53]': {
            required: true
        }
}

但可以肯定的是,由于名称属性中的数字,它不起作用。

我认为rules: 部分中的通配符tx_powermail_pi1[uid53][*] 可能会有所帮助,但它没有。

我希望必须选中此组中至少 1 个复选框。

【问题讨论】:

  • 我不确定它是否有效,但请尝试 [name^="tx_powermail_pi1"] 否则给他们一个通用类
  • rules 选项一次只接受 一个 完整的name 声明的规则; idclass、jQuery 选择器和通配符都不允许。您必须在 jQuery .each() 中使用 .rules('add') 方法。由于每个复选框都有不同的name,因此您必须使用require_from_group 规则。请参阅下面的答案。

标签: jquery checkbox jquery-validate


【解决方案1】:

如果您只想在组外设置一个复选框(当组中的每个成员都有不同的name),请使用require_from_group 方法,它是the additional-methods.js file 的一部分。

您还可以通过在 jQuery .each() 中使用 the .rules() method 来节省多行代码。

定位所有元素tx_powermail_pi1[uid53]开始。

$('input[name^="tx_powermail_pi1[uid53]"]').each(function () {
    $(this).rules('add', {
        require_from_group: [1, this],
        messages: {
            require_from_group: "please check one"
        }
    });
});

然后要将所有三个重复的消息合并为一个,请使用groups 选项...

$('#formid').validate({
    // other rules & options
    groups: {
        checkbox: 'tx_powermail_pi1[uid53][0] tx_powermail_pi1[uid53][3] tx_powermail_pi1[uid53][4]'
    }
});

工作演示:http://jsfiddle.net/xLNVf/2/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多