如何从下拉列表中填写表单数据


How fill form data from Dropdown?

我在页面上有一个表单,用户可以在其中保存信息,还有一个下拉列表,可以将保存的文件从他们保存的目录中拉出。我想要的是,当他们转到该页面时,当他们从下拉框中选择文件名时,它会将文件名放在输入框"CodeDescription"字段中,并将文件信息放在文本区域"代码"中,但是我不确定如何解析它。下面是我当前的代码。

<input type="hidden" name="Action" value="EDIT" />
<input type="hidden" name="Selection"  id="Selection" value="-1">    
<div>Below is the list of your saved codes. To edit your codes, select it from the list.</div>
<select> 
<?php 
  $directory = $directory = 'users/' . $_SESSION['username'];
  $files = scandir( $directory ) ;
  foreach( $files as $file ) {
    if ( ! is_dir( $file ) ) {
      echo "<option>" . $file . "</option>";
    }
  }
  ?>
</select>
<h3>Saved Codes</h3>
<form method="post" action="/evo/avsaveprocess.php">
  <input type="hidden" name="Action" value="SAVE" />
  <input type="hidden" name="CodeId" id="CodeId" value="0" />
  <table width="100%" border="0">
    <tr>
      <td>Description:</td>
      <td><input type="text" name="CodeDescription" size="40" maxlength="50" id="CodeName" value="" /></td>
    </tr>
    <tr>
      <td valign="top">Code:</td>
      <td>
        <textarea rows="10" style="width:99%" name="Code" id="CodeValue"></textarea>
      </td>
    </tr>
  </table>
  <input type="submit" value="Save" />
</form>

或者,相反,我不介意在下拉菜单中选择正确的文件时,它只是在表单字段下方显示输出。

编辑以添加我正在尝试的JavaScript:

<script>
function CodeChange() {                            
        var filesContentJS = "$filesContents";
        if (index > 0) {
            document.getElementById("Selection").value = filesContentJS;
          } else {
            document.getElementById("Selection").value = "-1";
            document.getElementById("CodeId").value = "0";
            document.getElementById("CodeName").value = "";
            document.getElementById("CodeValue").value = "";
        }
    }
</script>

更新的 javascript 这不会输出任何错误,但是当我检查 Chrome 中的元素时,它会返回:

警告:file_get_contents(users/AddictionAddiction.txt) [function.file-get-content]:无法打开流:在/home/revo/public_html/evo/codesaveindex.php 第 141 行中没有这样的文件或目录

我不确定在哪里纠正,因为成瘾成瘾之间应该有一个/.txt

创建文件内容数组:

<?php 
$directory = $directory = 'users/' . $_SESSION['username'];
$filesContents = Array();
$files = scandir( $directory ) ;
foreach( $files as $file )
{
if ( ! is_dir( $file ) )
{
$filesContents[$file] = file_get_contents($directory . $file);
echo "<option>" . $file . "</option>";
}
}
?>

然后使其成为Javascript数组或JSON

<script>
var filesContentJS = <?=json_encode($filesContents) ?>;
</script>

在选择中使用onChange="函数:从下拉列表中获取所选文件,滚动浏览filesContentJS以查找其内容并填写表单


另一方面:请记住,如果您的文件很大(有很多代码/文本) - 您可能需要使用 AJAX 执行此操作...当下拉列表更改时,执行 AJAX 调用以检索其信息。