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

基于select选择的jQuery代码改写:required属性添加及双触发逻辑实现问题

修复后代码

// 逻辑封装为公共函数,支持多场景调用
function validateTotalRequired() {
    const statusSelect = document.getElementById("StatusID");
    const selectedStatus = statusSelect.options[statusSelect.selectedIndex].value;
    const totalInput = document.getElementById('_total');
    
    if(totalInput.value == 0) {
        $(".Star").css('display','inline-block');
        totalInput.setAttribute("required", "required");
        // 兼容jQuery写法可选:$('#_total').prop('required', true)
    } else {
        $(".Star").css('display','none');
        totalInput.removeAttribute("required");
        // 兼容jQuery写法可选:$('#_total').prop('required', false)
    }
}

// 页面加载完成后自动执行
$(document).ready(function() {
    validateTotalRequired();
    // 绑定select值变更触发逻辑
    $("#StatusID").change(function() {
        validateTotalRequired();
    });
});

问题修复说明

  • required属性设置失败:原代码setAttribute("required", "")传入空值存在浏览器兼容问题,改为传入标准有效值"required",同时补充不满足条件时移除属性的逻辑,避免表单校验异常
  • 触发时机覆盖:将核心逻辑封装为独立函数,分别在页面加载完成、select值变更两个场景调用,满足需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 23:54:01