繁体   English   中英

遇到问题 javascript 文件不响应 html 表单

[英]Having trouble with the javascript file does not respond to html form

我正在尝试制作一个 javascript 文件来检查注册表单的规则,但警报没有弹出,所以我不知道哪个部分不起作用。

当我单击提交按钮时,它会直接转到 PHP 文件,而不是在警报 window 中列出消息。

function validate() {
    var name = document.getElementById("name").value;
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    var confirmPassword = document.getElementById("confirm-password").value;
    var genderM = document.getElementById("gender-male").checked; //radio
    var genderF = document.getElementById("gender-female").checked; //radio
    var temperature = document.getElementById("temperature").checked; //checkbox
    var favourite = document.getElementById("favourite").checked; //select
    var email = document.getElementById("email").value;
    var errMsg = "";
    var result = true;

    if (name == "") {
        errMsg += "Please enter a name.\n";
    }
    
    if (username == "") {
        errMsg  += "Please enter a username.\n";
    }

    if (password == "") {
        errMsg += "Please enter a password.\n";
    }

    if (confirmPassword == "") {
        errMsg += "Please re-enter password.\n";
    }

    if (password != confirmPassword) {
        errMsg += "Confirm password does not match.\n";
    }

    if (email == "") {
        errMsg += "Please enter an email address.\n";
    }

    if (email.indexof('@') == 0) {
        errMsg += "Email address invalid.\n";
    }

    if (email.indexof('@') < 0) {
        errMsg += "Email address must contain an @ symbol.\n";
    }

    if ((genderM = "" )&&(genderF = "")) {
        errMsg += "Please enter a gender.\n";
    }

    if (temperature == "") {
        errMsg += "Please enter a drink temperature.\n";
    }

    if (favourite == "") {
        errMsg += "Please enter a favourite drink.\n";
    }

    if (errMsg != "") {
        alert (errMsg);
        result = false;
    }
    return result;
}

function init() {
    var register = document.getElementById("register"); //form id="register"
    register.onsubmit = validate;
}

window.onload = init();

我试图仔细检查所有可能的错误,例如缺少“;” 或错误的元素等。但是,似乎没有什么对我有用。

尝试这个

window.onload = init // assign function instead of calling it

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM