【问题标题】:How to clear form elements that are pre-populated with $_POST values如何清除预先填充了 $_POST 值的表单元素
【发布时间】:2017-05-19 16:29:13
【问题描述】:

如果您运行并提交以下表单:

<!DOCTYPE html>
<html>
<body>
<form action="" method="POST">
  First name:<br>
  <input type="text" name="firstname" value="<?php if(isset($_POST['firstname'])){echo $_POST['firstname'];} ?>"
  <br>
  <input type="submit" value="Submit">
  <input type="button" onclick="this.form.reset()" value="Clear Form">
</form> 
</body>
</html>

当表单预先填充了之前提交的值时,为什么this.form.reset() 不起作用?清除表单按钮仅在提交数据之前有效。我也尝试了许多使用 jQuery 的类似方法,这些方法也只能在提交表单之前工作,之后再也不工作。

由于 JavaScript 在服务器端代码之后运行,我希望 $_POST['firstname'] 中的值可以替换为 JavaScript(在本例中为空字符串)。

【问题讨论】:

标签: javascript php jquery forms post


【解决方案1】:

正如@Taplar 所建议的,reset 将设置页面加载时最初设置的值。不要混淆“重置”表单值与将值设置为“”(空白字符串)

试试这个:

HTML:

<input type="text" id="fn" name="firstname" value="preloaded value" />
<input type="button" onclick="clear_form();" value="Clear Form">

JAVASCRIPT:

function clear_form() {
    document.getElementById('fn').value = "";
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 2018-05-12
    • 2016-01-26
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    相关资源
    最近更新 更多