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

jQuery脚本问题:文本框非空判断有效,复选框选中判断失效

Fixing Your Form Validation Logic

Let's walk through the issues in your code and fix them to meet your requirement (users must fill either the textbox or check the checkbox):

Key Issues Identified

  1. Duplicate jQuery Includes: You added two versions of jQuery (1.8.3 and 1.8.2), which can cause conflicts. Stick to one version.
  2. Incorrect Textbox Selector: You used TextBoxID instead of ClientID for the textbox control—this means your script can't find the textbox element.
  3. Syntax Error in Checkbox Condition: The if statement for the checkbox is missing parentheses around the condition, which breaks code execution.
  4. Missing Combined Validation Logic: Your current code checks each field separately but doesn't enforce the "either/or" requirement.

Corrected Script

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $('#<%= lbtnSave.ClientID %>').click(function (e) {
        // Get references to controls using correct ClientID
        var txtConsent = $('#<%= txtPhotoAndVideoConsentIfNot.ClientID %>');
        var cbConsent = $('#<%= cbPhotoAndVideoConsent.ClientID %>');
        
        // Check if textbox has non-empty value OR checkbox is checked
        var isTextboxFilled = $.trim(txtConsent.val()) !== '';
        var isCheckboxChecked = cbConsent.is(':checked');
        
        if (!isTextboxFilled && !isCheckboxChecked) {
            // Neither is valid—show error and stop form submission
            alert('Please either fill in the textbox or check the checkbox.');
            e.preventDefault(); // Prevent button postback
        } else {
            // At least one is valid—add further logic here if needed
            alert('Validation passed!');
        }
    });
});
</script>

Explanation of Fixes

  • Removed Duplicate jQuery: We kept the newer 1.8.3 version to avoid conflicts.
  • Fixed Textbox Selector: Changed TextBoxID to ClientID so jQuery can correctly locate the textbox element.
  • Fixed Checkbox Syntax: Integrated the checkbox check into a cleaner combined validation (no more missing parentheses).
  • Added Combined Validation: We now check if either the textbox has trimmed content (ignoring whitespace) or the checkbox is checked. If neither is true, we show an error and block form submission.
  • Trimmed Textbox Value: Using $.trim() ensures users can't bypass validation by entering only spaces.

This script will properly enforce your requirement and resolve the issues with both the textbox and checkbox checks.

内容的提问来源于stack exchange,提问作者p.developer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:34:13