提交时不会显示JavaScript警报

时间:2014-09-14 04:01:08

标签: javascript

尝试使用JavaScript验证创建一个简单表单,以便在文本字段为空时提醒用户。当我在浏览器中打开已保存的.html文件时,表单会出现,但是当我点击提交时,没有出现任何JavaScript警报,如何使这个JavaScript功能工作并在提交时显示警告?

<!DOCTYPE html>
<html>
<head>
<script>

function validateForm() {

var errormessage= "";


    if (document.getElementsById('fullName').value ==""){errormessage += "First name must be filled out \n";
        }
    }

    if (document.getElementsById('fullName').value ==""){errormessage += "First name must be filled out \n";
        }
    }
    if (document.getElementsById('pNumber').value ==""){errormessage += "First name must be filled out \n";
        }
    }

    if (document.getElementsById('eMail').value ==""){errormessage += "First name must be filled out \n";
        }
    }

     if (document.getElementsById('aMessage').value ==""){errormessage += "First name must be filled out \n";
        }
    }   

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


</script>
</head>

<body>

<form method="post" action="#" onsubmit="return validateForm ()">

<fieldset>
    <label>Your Name: 
    <input type="text" id="fullName" name="fullName"></label>
    <br>
    <label>Your Phone Number: 
    <input type="text" id="pNumber" name="pNumber"></label>
    <br>
    <label>Your Email Address: 
    <input type="text" id="eMail" name="eMail"></label>
    <br>
    <label>Message: 
    <input type="text" id="aMessage" name="aMessage"></label>
    <br>
    <input type="submit" value="click to submit">
</fieldset>
</form>
</body>

</html>

1 个答案:

答案 0 :(得分:2)

有两个问题

1 应该有getElementById

2 }声明之后,你有两倍if。只需一个}

这对您有用

function validateForm() {
    var errormessage= "";
    if (document.getElementById('fullName').value ==""){
        errormessage += "Name must be filled out \n";
    }
    if (document.getElementById('pNumber').value ==""){
        errormessage += "Phone Number must be filled out \n";
    }
    if (document.getElementById('eMail').value ==""){
        errormessage += "Email must be filled out \n";
    }
    if (document.getElementById('aMessage').value ==""){
        errormessage += "Message must be filled out \n";
    }   
    if (errormessage !="") {
        alert(errormessage);
        return false;
    }
}