You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在JavaScript中验证动态生成的多组textarea与select控件

Let's get this dynamic control validation sorted out. The core problem here is that your original validation wasn't pairing each select with its corresponding textarea—we need to explicitly link each group so we can validate them as a set, even when they're generated server-side.

Step 1: Ensure Server-Side Controls Have Linked Identifiers

First, when generating your DropDownList and TextBox (multi-line) controls in VB, give them matching IDs with a consistent prefix. This makes it easy to find the paired control in JavaScript. For example:

' Example VB code to generate dynamic control groups
Dim groupCount As Integer = 5 ' Replace with your actual group count
For i As Integer = 0 To groupCount - 1
    ' Create Select (DropDownList)
    Dim yesNoSelect As New DropDownList()
    yesNoSelect.ID = $"sel_group_{i}"
    yesNoSelect.Items.Add(New ListItem("Select an option", ""))
    yesNoSelect.Items.Add(New ListItem("Yes", "Y"))
    yesNoSelect.Items.Add(New ListItem("No", "N"))
    divTarget.Controls.Add(yesNoSelect) ' divTarget is your ASP.NET Panel/Div

    ' Create TextArea (MultiLine TextBox)
    Dim responseText As New TextBox()
    responseText.ID = $"txt_group_{i}"
    responseText.TextMode = TextBoxMode.MultiLine
    responseText.Rows = 3
    responseText.Columns = 50
    divTarget.Controls.Add(responseText)

    ' Add spacing between groups
    divTarget.Controls.Add(New LiteralControl("<br><br>"))
Next

Step 2: Updated JavaScript Validation Function

This function will loop through every dynamic select, find its paired textarea, and validate all three rules for each group:

function validateDynamicGroups() {
    let isFormValid = true;
    const validationErrors = [];

    // Grab all dynamically generated select controls
    const allSelects = document.querySelectorAll('select[id^="sel_group_"]');

    allSelects.forEach(select => {
        // Find the matching textarea by swapping the ID prefix
        const textareaId = select.id.replace('sel_group_', 'txt_group_');
        const pairedTextarea = document.getElementById(textareaId);

        if (!pairedTextarea) {
            validationErrors.push(`Missing textarea for group ${select.id.split('_').pop()}`);
            isFormValid = false;
            select.classList.add('validation-error');
            return;
        }

        // Rule 1: Must select Yes or No (no empty option)
        if (select.value === "") {
            validationErrors.push(`Please select Yes/No for group ${select.id.split('_').pop()}`);
            isFormValid = false;
            select.classList.add('validation-error');
            return;
        } else {
            select.classList.remove('validation-error');
        }

        // Rule 2: If Yes is selected, textarea must have 1-1000 characters
        if (select.value === "Y") {
            // First ensure the textarea is enabled
            if (pairedTextarea.disabled) {
                validationErrors.push(`Textarea for group ${select.id.split('_').pop()} must be enabled when selecting Yes`);
                isFormValid = false;
                pairedTextarea.classList.add('validation-error');
                return;
            }

            const textLength = pairedTextarea.value.trim().length;
            if (textLength < 1 || textLength > 1000) {
                validationErrors.push(`Group ${select.id.split('_').pop()}: Textarea must contain 1-1000 characters`);
                isFormValid = false;
                pairedTextarea.classList.add('validation-error');
            } else {
                pairedTextarea.classList.remove('validation-error');
            }
        } 
        // Rule 3: If No is selected, textarea must be disabled
        else if (select.value === "N") {
            if (!pairedTextarea.disabled) {
                validationErrors.push(`Group ${select.id.split('_').pop()}: Textarea must be disabled when selecting No`);
                isFormValid = false;
                pairedTextarea.classList.add('validation-error');
            } else {
                pairedTextarea.classList.remove('validation-error');
            }
        }
    });

    // Show errors if any
    if (!isFormValid) {
        alert(validationErrors.join('\n'));
        return false;
    }

    return true;
}

Step 3: Add User Experience Improvements

To make this smoother for users, add a change event listener to automatically enable/disable the textarea when the select is updated. This ensures users don't accidentally enter text when they select No:

// Auto-enable/disable textarea on select change
document.addEventListener('DOMContentLoaded', function() {
    const allSelects = document.querySelectorAll('select[id^="sel_group_"]');
    allSelects.forEach(select => {
        select.addEventListener('change', function() {
            const textareaId = this.id.replace('sel_group_', 'txt_group_');
            const pairedTextarea = document.getElementById(textareaId);
            if (pairedTextarea) {
                pairedTextarea.disabled = this.value === "N";
                // Optional: Clear text when disabling
                if (this.value === "N") {
                    pairedTextarea.value = "";
                }
            }
        });
    });
});

Step 4: Hook the Validation to Your Submit Button

Finally, attach the validation function to your submit button's client-side click event:

<asp:Button ID="btnSubmit" runat="server" Text="Submit" 
    OnClientClick="return validateDynamicGroups();" 
    OnClick="btnSubmit_Click" />

This setup will validate every dynamic control group correctly, ensuring each select and textarea are paired and follow your rules.

内容的提问来源于stack exchange,提问作者Santosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:48:02