简体   繁体   English

Javascript 使用数组值验证复选框

[英]Javascript validate checkboxes with array values

Plot I have some dynamic js validations that first scan for all fields in a step (HTMLElement).情节我有一些动态 js 验证,首先扫描步骤中的所有字段(HTMLElement)。 Basically I populate checkbox_groups with all the names and then check if at least one is checked.基本上,我用所有名称填充checkbox_groups ,然后检查是否至少检查了一个。 This works good except a certain situation.除了某些情况外,这很好用。

Problem I have some dynamic checkboxes that have names like: person[1] , person[2] , person[3] .问题我有一些动态复选框,其名称如下: person[1]person[2]person[3] Because the id is specified my error <p> appears under each checkbox instead of only the last checkboxes as intended.因为指定了 id,所以我的错误<p>出现在每个复选框下,而不是像预期的那样仅显示最后一个复选框。 Basically all I want is to find a way to modify this script so in this scenario the error message to appear only after the last checkbox.基本上我想要的是找到一种方法来修改这个脚本,所以在这种情况下,错误消息只出现在最后一个复选框之后。

Code代码

/**
 * Validate step checkboxes
 *
 * @param {HTMLElement} element
 *
 * @returns {Object}
 */
function validate_step_checkboxes(step) {
    var checkbox_groups = [];
    var errors = [];
    var error = false;

    $.each(step.find('input[type="checkbox"][data-required="1"]'), function () {
        var myname = this.name;
        if ($.inArray(myname, checkbox_groups) < 0) {
            checkbox_groups.push(myname);
        }
    });

    console.log('groups');
    console.log(checkbox_groups);

    // Check if there is a checkbox selected for each checkbox group
    for (i = 0; i < checkbox_groups.length; i++) {
        if (step.find('input[type="checkbox"][data-required="1"]:checked').length <= 0) {
            $('input[type="checkbox"][data-required="1"][name="' + checkbox_groups[i] + '"]').last().closest('.checkbox-label').after('<p class="input-error">Please select one option.</p>');
            errors[checkbox_groups[i]] = 'Field required';
            error = true;
        }
    }
    return !error;
}

HTML HTML

<table class="primary-table hidden-xs">
    <thead>
        <tr>
            <th>Name</th>
            <th>X/th>
            <th>x</th>
            <th>x</th>
            <th>&emsp;</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <label class="checkbox-label">Test PErson
                <input name="person[1]" type="checkbox" data-required="1">
                <span class="checkmark"></span>
                </label>
            </td>
            <td>-</td>
            <td>Test</td>
            <td>Test</td>
            <td><a href="h#">Edit</a></td>
        </tr>
        <tr>
            <td>
                <label class="checkbox-label">Test PErson
                <input name="person[2]" type="checkbox" data-required="1">
                <span class="checkmark"></span>
                </label>
            </td>
            <td>-</td>
            <td>Test</td>
            <td>Test</td>
            <td><a href="h#">Edit</a></td>
        </tr>
        <tr>
            <td>
                <label class="checkbox-label">Test PErson
                <input name="person[3]" type="checkbox" data-required="1">
                <span class="checkmark"></span>
                </label>
            </td>
            <td>-</td>
            <td>Test</td>
            <td>Test</td>
            <td><a href="h#">Edit</a></td>
        </tr>
        <tr>
            <td>
                <label class="checkbox-label">Test PErson
                <input name="person[4]" type="checkbox" data-required="1">
                <span class="checkmark"></span>
                </label>
            </td>
            <td>-</td>
            <td>Test</td>
            <td>Test</td>
            <td><a href="h#">Edit</a></td>
        </tr>
    </tbody>
</table>

As described in the comments, the HTML defines each individual checkbox as part of a unique set (eg person[1] ).如评论中所述,HTML 将每个单独的复选框定义为唯一集合的一部分(例如person[1] )。 But the Javascript expects those to be groups of checkboxes ...但是 Javascript 期望那些是复选框......

There is nothing wrong with using a checkbox name like person , you can still have 10 checkboxes with that name and check as many or as few as you like.使用像person这样的复选框名称并没有错,您仍然可以拥有 10 个具有该名称的复选框,并根据需要检查任意数量的复选框。 To make things easier on the backend it is common to use a name like person[] , so you get an array of values.为了使后端的事情更容易,通常使用person[]之类的名称,因此您会得到一个值数组。 In this case since you're selecting multiple persons maybe people[] is an appropriate name.在这种情况下,由于您要选择多个人,因此people[]可能是一个合适的名称。

If you really need unique name s for each checkbox for some reason, the only way I can think of to get the JS to treat them as part of a single group is to strip off the [1] part to find the common "base" name.如果出于某种原因您确实需要每个复选框的唯一name ,我能想到的让 JS 将它们视为单个组的一部分的唯一方法是剥离[1]部分以找到共同的“基础”姓名。 This does not seem like a good idea though, fragile and hacky.不过,这似乎不是一个好主意,既脆弱又笨拙。 I've included a working example below, but I wouldn't recommend using this.我在下面提供了一个工作示例,但我不建议使用它。

Maybe a better option would be to treat the block of HTML as the semantic group?也许更好的选择是将 HTML 块视为语义组? So the input name isn't relevant, you're just looking for something checked inside that <div> (or maybe <table> in your case)?所以输入name不相关,您只是在寻找在<div> (或者可能是<table>在您的情况下)中检查的内容? But again this doesn't feel like a good option, we're circumventing the built in properties that are supposed to do exactly this - the name specifies how inputs are grouped.但这又不是一个好的选择,我们绕过了应该完全做到这一点的内置属性 - name指定了输入的分组方式。

 /** * Validate step checkboxes * * @param {HTMLElement} element * * @returns {Object} */ function validate_step_checkboxes(step) { var checkbox_groups = []; var errors = []; var error = false; $.each(step.find('input[type="checkbox"][data-required="1"]'), function () { var myname = this.name; // Check if this name includes [1], etc if (myname.match(/\[\d\]/)) { // It does, let's get the "base name" without [1] myname = myname.replace(/\[\d\]/, ''); console.log('stripped', myname); } if ($.inArray(myname, checkbox_groups) < 0) { checkbox_groups.push(myname); } }); console.log('groups'); console.dir(checkbox_groups); // Check if there is a checkbox selected for each checkbox group for (i = 0; i < checkbox_groups.length; i++) { if (step.find('input[type="checkbox"][data-required="1"]:checked').length <= 0) { $('input[type="checkbox"][data-required="1"][name^="' + checkbox_groups[i] + '"]').last().closest('.checkbox-label').after('<p class="input-error">Please select one option.</p>'); errors[checkbox_groups[i]] = 'Field required'; error = true; } } console.log('errors:'); console.dir(errors); return !error; } $(document).ready(function() { let $step1 = $('.primary-table'); let valid = validate_step_checkboxes($step1); console.log('valid:', valid); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table class="primary-table hidden-xs"> <thead> <tr> <th>Name</th> <th>X/<th> <th>x</th> <th>x</th> <th>&emsp;</th> </tr> </thead> <tbody> <tr> <td> <label class="checkbox-label">Test PErson <input name="person[1]" type="checkbox" data-required="1"> <span class="checkmark"></span> </label> </td> <td>-</td> <td>Test</td> <td>Test</td> <td><a href="h#">Edit</a></td> </tr> <tr> <td> <label class="checkbox-label">Test PErson <input name="person[2]" type="checkbox" data-required="1"> <span class="checkmark"></span> </label> </td> <td>-</td> <td>Test</td> <td>Test</td> <td><a href="h#">Edit</a></td> </tr> <tr> <td> <label class="checkbox-label">Test PErson <input name="person[3]" type="checkbox" data-required="1"> <span class="checkmark"></span> </label> </td> <td>-</td> <td>Test</td> <td>Test</td> <td><a href="h#">Edit</a></td> </tr> <tr> <td> <label class="checkbox-label">Test PErson <input name="person[4]" type="checkbox" data-required="1"> <span class="checkmark"></span> </label> </td> <td>-</td> <td>Test</td> <td>Test</td> <td><a href="h#">Edit</a></td> </tr> </tbody> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM