Javascript表单验证onSubmit不触发

时间:2012-10-18 09:25:43

标签: javascript forms validation

请有人帮忙。这个表单验证没有触发..这真让我很沮丧。我是一个PHP开发人员而不是JS,所以我对此有点挣扎,尽管它显然非常简单。我只是想根据勾选的删除框验证表单。

点击提交时没有显示任何内容。它只是提交表单,所以它必须返回true。

function deleteVal(chk) {

    var chk;

    // If the checkbox has been set to delete
    if (chk.checked == "delete") {

        var ok=confirm("You are about to delete the selected images below.\nAre you sure you want to do this?");

        if (ok) {

            // Submit
            return true;

        } else {

            // Don't submit
            return false;

        }

    }

    // Delete box was not ticked so return true and submit form
    return true;

}

</script>

<form action="" method="POST" onSubmit="return deleteVal(delete)">
  <label>Delete images?</label><input type="checkbox" name="delete" value="delete" />
  <input type="submit" name="submit" value="Submit" />
</form>

1 个答案:

答案 0 :(得分:2)

您需要正确获取checked值,看看它是真还是假。

var chk = document.getElementById('delete');

// If the checkbox is checked
if (chk.checked == true) {

然后你不需要将变量传递给函数,但是,你需要给你一个复选框id。

<form action="" method="POST" onSubmit="return deleteVal();">
  <input type="checkbox" name="delete" id="delete"/>
  <input type="submit" name="submit" value="Submit" />
</form>

经过测试的代码 - http://pastebin.com/FdWdeSCN