3

我有一个用于从 MySQL 数据库提交和检索数据的 HTML 表单,带有两个按钮,“保存/提交”和“新建/重置”它从 MySQL 数据库中正确获取数据但是当我单击新建/重置按钮以获取新联系人条目时'不清除表单文本字段。我的 HTML 和 PHP 代码如下:

<?php
//Database Connection file.
include'connect.php';
$sql = mysql_query("SELECT * FROM contact_list WHERE id='1'");
While($result = mysql_fetch_assoc($sql)){
   $fname = $result['fname'];
   $lname = $result['lname'];
   $email = $result['email'];
   $contact = $result['contact'];
}

if(isset($_POST['fname'])&&isset($_POST['lname'])&&isset($_POST['email'])&&
isset($_POST['contact'])){
   $fname = $_POST['fname'];
   $lname = $_POST['lname'];
   $email = $_POST['email'];
   $contact = $_POST['contact'];

if($sql = mysql_query("INSERT INTO contact_list VALUES ('', '$fname', '$lname',
'$email', '$contact')")){
   echo'Contact Save Successfully.';
}else{
   echo'Contact not save.';
}
}
?>
<html>
<form action="sample.php" method="POST">
   First Name:<input type="text" name="fname" value="<?php if(isset($fname))
   {echo $fname;}?>">
   Last Name:<input type="text" name="lname" value="<?php if(isset($lname))
   {echo $lname;}?>">
   Email:<input type="text" name="email" value="<?php if(isset($email))
   {echo $email;}?>">
   Contact:<input type="text" name="contact" value="<?php if(isset($contact))
   {echo $contact;}?>">
//Clean all fields of forms for new entry.
   <input type="reset" value="New">
//Save or submit form data into mysql database
   <input type="submit" value="Save">
</form>
</html>
4

1 回答 1

1

您可以使用 jQuery 轻松完成此操作

<html>
<head>
<script type="text/javascript">
$(document).ready(function() {
    $("#btnReset").click(function(){
       $("#fname").val("");
       $("#lname").val("");
       $("#email").val("");
       $("#contact").val("");
    }); 
});

</script>
</head>
<form action="sample.php" method="POST">
   First Name:<input type="text" name="fname" value="<?php if(isset($fname))
   {echo $fname;}?>" id="fname">
   Last Name:<input type="text" name="lname" value="<?php if(isset($lname))
   {echo $lname;}?>" id="lname">
   Email:<input type="text" name="email" value="<?php if(isset($email))
   {echo $email;}?>" id="email">
   Contact:<input type="text" name="contact" value="<?php if(isset($contact))
   {echo $contact;}?>" id="contact">
//Clean all fields of forms for new entry.
   <input type="reset" value="New" id="btnReset">
//Save or submit form data into mysql database
   <input type="submit" value="Save" id="btnSave">
</form>
</html>
于 2013-05-21T12:17:18.753 回答