2 回答
TA贡献1828条经验 获得超13个赞
看起来您可能正在使用 asp.net Webforms,它可能会受到id/name mangling 的影响,特别是在母版页发挥作用的情况下。
让我们使用数据属性来帮助我们识别组。例如:
<asp:TextBox runat="server" data-requiredgroup="group1" TextMode="text" ID="id1" class="form-control-login" required=""></asp:TextBox>
<asp:TextBox runat="server" data-requiredgroup="group1" TextMode="text" ID="id2" class="form-control-login" required=""></asp:TextBox>
出于演示目的,我将使用纯 HTML 来连接 javascript,但它仍然应该可以很好地与您的 Web 表单配合使用
//Get using our data attribute, don't need to worry about name mangling
var groups = document.querySelectorAll("[data-requiredgroup]");
for (var i = 0; i < groups.length; i++) {
//Add Event Listener
groups[i].addEventListener("keyup", function() {
//Get group
let group = document.querySelectorAll("[data-requiredgroup=" + this.dataset.requiredgroup + "]");
for (var g = 0; g < group.length; g++) {
//Remove if not empty
if (group[g] != this) {
group[g].required = (this.value == "");
}
}
});
}
input:required {
border-color:red;
}
<div>
Group 1
<input type="text" data-requiredgroup="group1" required />
<input type="text" data-requiredgroup="group1" required />
</div>
<div>
Group 2
<input type="text" data-requiredgroup="group2" required />
<input type="text" data-requiredgroup="group2" required />
<input type="text" data-requiredgroup="group2" required />
<input type="text" data-requiredgroup="group2" required />
</div>
TA贡献1900条经验 获得超5个赞
尝试使用以下 JavaScript 代码:
var input1 = document.getElementById("id1");
var input2 = document.getElementById("id2");
input1.addEventListener('keypress', function() {
input1.removeAttribute("required");
input2.removeAttribute("required");
});
input2.addEventListener('keypress', function() {
input1.removeAttribute("required");
input2.removeAttribute("required");
});
添加回答
举报