0

i have this sample html coding

<form id = "myform" onsubmit = "return checkcheckboxes()">
task 1</task><input type = "checkbox" name = "chk1"></br>
task 2<input type = "checkbox" name = "chk2"></br>
task 3<input type = "checkbox" name = "chk3"></br></br>
<input type = "submit" value = "Go to the next task"></br>
<span id = "message" >congratulations! you have completed all the task completely</span>
</form>

and this is the JS

function checkcheckboxes() {
document.getElementById("message").innerHTML = "";
var valid = true;
var f = document.getElementById("myform");
if (f.chk1.checked == false) {valid = false}
if (f.chk2.checked == false) {valid = false}
if (f.chk3.checked == false) {valid = false}
if (!valid) {document.getElementById("message").innerHTML = "You must check all three boxes to proceed"};
return valid;
}

If you open the code in the browser with JS, it will show you three checkboxes with a submit button and there is a span text under submit button saying

congratulations! you have completed all the tasks completely

If you check >2 boxes and click submit, the text under the submit button will say

You must check all three boxes to proceed

and if you check all 3 boxes the message will change again back to:

congratulations! you have completed all the tasks completely

what i want to do is remove the saying:

congratulations! you have completed all the tasks completely

and only show it when all the boxes are checked and submit button is click, since is showing even though boxes are not checked.

4

1 回答 1

1

我想要做的是删除这句话:“恭喜!您已完全完成所有任务”,并且仅在选中所有框并单击提交按钮时才显示它

使<span>空:<span id="message"></span>。并在您验证表单时让 JavaScript 填充它。

如果我想在文本中添加一个链接,我应该只在 javascript 字符串中使用 html 锚标记吗?例:恭喜!您已完全完成所有任务,这是链接

在这种情况下,请在“恭喜...”文本中添加链接并始终返回false,以便永远不会提交表单。

是否有一个javascript命令可以获取页面上的所有复选框,而不是放置每个复选框,因为我将创建一个巨大的清单

就在这里。这是最终代码(验证myform表单内的所有复选框并将锚标记添加到结果文本):

function checkcheckboxes() {
    var valid = true;
    var inputs = document.getElementById("myform").getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "checkbox") {
            if (!inputs[i].checked) {
                valid = false;
                break; // break as soon as it finds an unchecked
            }
        }
    }
    if (!valid) {
        document.getElementById("message").innerHTML = "You must check all boxes to proceed";
    } else {
        document.getElementById("message").innerHTML = "congratulations! you have completed all the tasks completely and <a href='http://www.google.com'>here is the link</a>.";
    }
    return false;
}

在此处查看工作演示代码

于 2013-06-02T21:52:35.530 回答