我正在使用表单的提交按钮,javascript应该告诉我是否有任何字段为空..但是尽管使用了onclick属性,但没有发生任何事情..有一些PHP代码拒绝存储数据。我是PHP和Javascript的初学者,所以任何想法?
<script language="javascript">
function valid()
{
var a=document.form2.i1.value;
var b=document.form2.pas.value;
var c=document.form2.pas1.value;
var d=document.form2.n1.value;
var e=document.form2.a1.value;
var f=document.form2.r1.value;
var g=document.form2.pin1.value;
var h=document.form2.phno1.value;
var i=document.form2.u1.value;
var j=document.form2.email1.value;
if(a!="y")
{
alert("Please accept the terms and conditions before registering.");
return false;
}
else if(d=="")
{
alert("Name required.");
return false;
}
else if(e=="")
{
alert("Age required.");
return false;
}
else if(e<18)
{
alert("You have to be atleast 18 to register.");
return false;
}
else if(f="")
{
alert("Gender required.");
return false;
}
else if(g=="" || isNan(g))
{
alert("Valid pincode required.");
return false;
}
else if(h==""|| isNan(h))
{
alert("Valid phone number required.");
return false;
}
else if(i=="")
{
alert("Username required.");
return false;
}
else if(j=="")
{
alert("Email required.");
return false;
}
else if(b=="" || c=="")
{
alert("Password required.");
return false;
}
else if(b!=c)
{
alert("Please make sure the passwords are identical.");
return false;
}
return true;
}
</script>
这是我以前称之为的声明:
<div id="apDiv3"><input name="reg1" type="submit" id="login-submit" value="Register" onclick="return valid()"/></div>
这是我用来创建表单的PHP代码:
<?php
if(isset($_POST['reg1']))
{
$name=$_POST['n1'];
$age=$_POST['a1'];
$gen=$_POST['r1'];
$phno=$_POST['phno1'];
$email=$_POST['email1'];
$pin=$_POST['pin1'];
$user=$_POST['u1'];
$pas=$_POST['pass'];
$pas1=$_POST['pass1'];
$i=$_POST['i1'];
$connection=mysqli_connect("localhost","root","");
if (!$connection) {
die("Database connection failed: " . mysqli_error($connection));
}
$db_select = mysqli_select_db($connection, "vinay");
if (!$db_select) {
die("Database selection failed: " . mysqli_error($db_select));
}
$q="insert into reg values('0','$name','$age','$gen','$phno','$email','$pin','$user','$pas')";
mysqli_query($q) or die(mysqli_error($q));
if(mysqli_affected_rows()>0)
{
header("location:index.php");
}
}
?>
答案 0 :(得分:0)
为什么在HTML5已经具有用于此目的的属性时,您希望使用JavaScript。使用pattern
和required
属性
有关参考,请参阅:http://www.w3schools.com/html/html5_form_attributes.asp