簡體   English   中英

Javascript 使用數組值驗證復選框

[英]Javascript validate checkboxes with array values

情節我有一些動態 js 驗證,首先掃描步驟中的所有字段(HTMLElement)。 基本上,我用所有名稱填充checkbox_groups ,然后檢查是否至少檢查了一個。 除了某些情況外,這很好用。

問題我有一些動態復選框,其名稱如下: person[1]person[2]person[3] 因為指定了 id,所以我的錯誤<p>出現在每個復選框下,而不是像預期的那樣僅顯示最后一個復選框。 基本上我想要的是找到一種方法來修改這個腳本,所以在這種情況下,錯誤消息只出現在最后一個復選框之后。

代碼

/**
 * 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

<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>

如評論中所述,HTML 將每個單獨的復選框定義為唯一集合的一部分(例如person[1] )。 但是 Javascript 期望那些是復選框......

使用像person這樣的復選框名稱並沒有錯,您仍然可以擁有 10 個具有該名稱的復選框,並根據需要檢查任意數量的復選框。 為了使后端的事情更容易,通常使用person[]之類的名稱,因此您會得到一個值數組。 在這種情況下,由於您要選擇多個人,因此people[]可能是一個合適的名稱。

如果出於某種原因您確實需要每個復選框的唯一name ,我能想到的讓 JS 將它們視為單個組的一部分的唯一方法是剝離[1]部分以找到共同的“基礎”姓名。 不過,這似乎不是一個好主意,既脆弱又笨拙。 我在下面提供了一個工作示例,但我不建議使用它。

也許更好的選擇是將 HTML 塊視為語義組? 所以輸入name不相關,您只是在尋找在<div> (或者可能是<table>在您的情況下)中檢查的內容? 但這又不是一個好的選擇,我們繞過了應該完全做到這一點的內置屬性 - 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