我有这个JS代码:
function validateForm() {
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
if (y==null || y=="") {
alert("Password name must be filled out");
return false;
}
}
和这个HTML:
<form action="page.php" method="post">
Name*: <input type="text" name="name"> <br>
Password*: <input type="password" name="password"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
如何让我的javascript代码适用于输入class="required"
答案 0 :(得分:1)
我修复了你的html代码并在进入PHP页面之前进行了验证
您的表单中有错误 - 您忘记添加表单名称&#34; myform&#34;所以它没有得到值,直到我添加这个因为javascript不知道从哪里获取值,我添加了一个名为&#34的值;好&#34;如果它是假的,其他一切都是假的,它不会将值返回到php服务器
希望这有帮助
<html>
<head>
<script type="text/javascript">
function validate_Form() {
var x=document.forms["myForm"]["name"].value;
var good = new Boolean(true);
if (x==null || x=="")
{
alert("Name must be filled out");
good = false;
}
var y=document.forms["myForm"]["password"].value;
if (y==null || y=="")
{
alert("Password name must be filled out");
good = false;
}
return good
}
</script>
</head>
<body>
<form name="myForm" action="page.php" method="post" onsubmit="return validate_Form()">
Name*: <input type="text" name="name"> <br>
Password*: <input type="password" name="password"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
答案 1 :(得分:0)
这对你有用。您需要将name_id和password_id更改为这些元素的id。您可以获取类名并检查它是否等于必需。
function validateForm() {
var name = document.getElementById('name_id').className;
var x = document.forms["myForm"]["name"].value;
if (name == "required") {
if (x == null || x == "")
{
alert("Name must be filled out");
return false;
}
}
var password = document.getElementById('password_id').className;
var y = document.forms["myForm"]["password"].value;
if (password == "required") {
if (y == null || y == "") {
alert("Password name must be filled out");
return false;
}
}
}
按类完成所有操作的方法是这样的:
<script>
function validateForm() {
var x = document.getElementsByClassName('required');
for(var i = 0; i < x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("Field must be filled out");
return false;
}
}
}
</script>
<form>
Name*: <input type="text" name="name" class="required"> <br>
Password*: <input type="password" name="password" class="required"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit" onclick="validateForm();return false;">
</form>
答案 2 :(得分:0)
试试这个:
function CheckRequired(){
var AllInputs = document.getElementsByTagName('input');
for(var i = 0; i < AllInputs.length; i++){
if (AllInputs[i].getAttribute('class') === 'required' && AllInputs[i].Value = "")
{
return false;
alert('Please fill out all required fields');
}
}
}
<form method="POST">
<input type="submit" value="Submit" onclick="return CheckRequired();">
</form>