我有以下代码用于提交表单 - 它目前没有多大作用,但我希望实现的是:
文本框docTitle
是必填字段。
如果yourName
文本框中包含文本,并且docTitle
文本框留空,则提交时将显示必填字段消息,并且yourName
文本框将保留其值。
我正在努力解决表单在提交后保留先前值的部分。
代码如下:
<?php
if(isset($_POST['submit'])) {
if(empty($docTitle)) {
} else {
if ((($_FILES["file"]["type"] == "application/pdf")) && ($_FILES["file"]["size"] < 2000000) && ($_POST["docTitle"] > "")) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"];
if (file_exists("upload/pdf/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES['file']['tmp_name'],
"upload/pdf/" . $_FILES["file"]["name"]);
}
}
}
else
{
echo "Invalid file";
}
}
}
?>
<form name="uploadAPdf" id="uploadAPdf" action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data">
<label for="text">Name: </label> <input type="text" name="yourName" id="yourName" /><br />
<label for="text">Document: </label> <input type="text" name="docTitle" id="docTitle" />
<?php if(isset($_POST['submit']) && empty($docTitle)) {
echo " Document title must be filled in...";
echo "<script type='text/javascript'>document.uploadAPdf.docTitle.focus();</script>";
} ?>
<br />
<label for="file">Select PDF to upload: </label> <input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
这不是
你想要的吗:
<?php
function postValue($name, $alt = '') {
return isset($_POST[$name]) ? $_POST[$name] : $alt;
}
?>
<label for="text">Name: </label> <input type="text" name="yourName" id="yourName" value="<?=htmlspecialchars(postValue('yourName'))?>" /><br />
<label for="text">Document: </label> <input type="text" name="docTitle" id="docTitle" value="<?=htmlspecialchars(postValue('yourName'))?>" />
这就是大多数表单的工作方式...
也许我错过了一些东西=)
编辑
这是我在不使用PHP框架时使用的函数:
<?php
function ifsetor($var, $alt = '') {
return isset($var) ? $var : $alt;
}
?>
将像这样使用:
<?php
$selectedOptions = ifsetor($_POST['options'], array());
?>
编辑
不相关:您可能希望将表单元素放在包装器中(而不是用<br>
分隔它们),如下所示:
<div class="form-element"><label>...</label><input .... /></div>
将
HTML 输入代码更改为:
<input type="text" name="docTitle" id="docTitle" value="<?php echo htmlspecialchars($_POST['docTitle']; ?>" />