JavaScript复选框onclick函数
我被简单的JavaScript函数卡住了,它与复选框验证有关。如果cb1被选中,我需要document.write,如果cb2被选中,则需要document.write。如果两者都没有检查,或者其中一个没有检查,那么什么也不写JavaScript复选框onclick函数,javascript,jquery,html,checkbox,Javascript,Jquery,Html,Checkbox,我被简单的JavaScript函数卡住了,它与复选框验证有关。如果cb1被选中,我需要document.write,如果cb2被选中,则需要document.write。如果两者都没有检查,或者其中一个没有检查,那么什么也不写 <html> <head> <title>TEST PAGE</title> <script type="text/javascript" src="submit.js"></script>
<html>
<head>
<title>TEST PAGE</title>
<script type="text/javascript" src="submit.js"></script>
</head>
<body>
<div style="width:100%"><input type="checkbox" id="cb1"></div>
<div style="width:100%"><input type="checkbox" id="cb2"></div>
<div style="width:100%"><input type="submit" name="execute" id="execute" value="Execute" onClick="run();"></div>
</body>
</html>
测试页
submit.js
function run() {
document.write('<div>' + "HERE GOES YOUR CHECKBOX CHOICE: " + '</div>');
if(document.getElementById("cb1").checked == true) {
document.write("This is check box 1");
}
if(document.getElementById("cb2").checked == true) {
document.write("This is check box 2");
}
}
函数运行(){
写(“+”这是您的复选框选择:“+”);
if(document.getElementById(“cb1”).checked==true){
文件。填写(“这是复选框1”);
}
if(document.getElementById(“cb2”).checked==true){
文件。填写(“这是复选框2”);
}
}
您不应该使用document.write。
使用“附加到标记”
像
$(“#divid”).append($(“”,{type:“checkbox”,onclick:“yourfunction(this)”});
只需在jquery的javascript中使用.checked
即可使用.prop('checked')
函数运行(){
if(document.getElementById(“cb1”).已选中){
文件。填写(“这是复选框1”);
}
if(document.getElementById(“cb2”).已选中){
文件。填写(“这是复选框2”);
}
}
正如前面的一个答案中提到的,您不应该使用document.write
。您可以使用.append(string)
向文档中添加内容:
document.append('Both boxes are checked');
下面是一个改进的运行函数:
function run() {
var snip = "<div>HERE GOES YOUR CHECKBOX CHOICE: </div>";
if(document.getElementById("cb1").checked == true) {
snip += "<br/>This is check box 1";
}
if(document.getElementById("cb2").checked == true) {
snip += "This is check box 2";
}
document.write(snip);
}
函数运行(){
var snip=“这是您的复选框选择:”;
if(document.getElementById(“cb1”).checked==true){
snip+=“
这是复选框1”;
}
if(document.getElementById(“cb2”).checked==true){
snip+=“这是复选框2”;
}
文件。编写(snip);
}
每个人都发现了在实际读取元素之前覆盖html的错误,因此这就是导致错误的原因,清除DOM,然后尝试读取不再存在的输入属性。您到底遇到了什么问题?您正在寻找jQuery解决方案吗?您使用了标记,但没有jQuery代码。这就是我需要的。谢谢你的解决方案。
if (document.getElementById('cb1').checked && document.getElementById('cb2').checked) {
// both are checked
}
else {
// only one or none are checked
}
document.append('Both boxes are checked');
function run() {
var snip = "<div>HERE GOES YOUR CHECKBOX CHOICE: </div>";
if(document.getElementById("cb1").checked == true) {
snip += "<br/>This is check box 1";
}
if(document.getElementById("cb2").checked == true) {
snip += "This is check box 2";
}
document.write(snip);
}