gpt4 book ai didi

javascript - 如果选中复选框,则需要输入

转载 作者:行者123 更新时间:2023-12-02 07:01:13 27 4
gpt4 key购买 nike

作为 Web 表单的一部分,我有两个复选框(均名为“my_checkbox”)和两个输入文件(一个名为“input1”,另一个名为“input2”)。

<input type="checkbox" name="my_checkbox" value="some text" onclick="a function;    checkBoxValidate(0);">

<input type="checkbox" name="my_checkbox" value="some diffrent text" onclick="a diffrent function; checkBoxValidate(1);">

<input id="input1" name="input1" />

<input id="input2" name="input2" />

如果用户选中第一个复选框,则 input1 不能为空。如果用户选择第二个复选框,则 input2 不能为空。这两个复选框必须具有相同的名称。函数 checkBoxValidate 确保不能同时选中两个复选框(我不喜欢单选按钮)。

我的javascript:

}else if (!document.myform.my_checkbox[0].checked && myform.input1.value == ''){ 
alert ('Please enter some text!',function(){$(myform.input1).focus();});
return false;

}else if (!document.myform.my_checkbox[1].checked && myform.input2.value == ''){
alert ('Please enter some text!',function(){$(myform.input2).focus();});
return false;

当然,没有任何效果!请帮忙? :)

最佳答案

看到你可能想把这个简单化,我把它写得简单并使用纯 JS,因为你没有用 jQuery 标记问题。

Live Demo

window.onload=function() {
var form1=document.getElementById("form1"); // assuming <form id="form1"
form1.onsubmit=function() {
if (this.my_checkbox[0].checked && this.input1.value=="") {
alert("Please enter something in input 1");
this.input1.focus();
return false;
}
if (this.my_checkbox[1].checked && this.input2.value=="") {
alert("Please enter something in input 2");
this.input2.focus();
return false;
}
return true; // allow submission
}
// if the checkboxes had different IDs this could have been one function
form1.my_checkbox[0].onclick=function() {
this.form.my_checkbox[1].checked=!this.checked;
}
form1.my_checkbox[1].onclick=function() {
this.form.my_checkbox[0].checked=!this.checked;
}
}

关于javascript - 如果选中复选框,则需要输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20439649/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com