Anthony
Anthony

Reputation: 742

How to clear form elements that are pre-populated with $_POST values

If you run and submit the form below:

<!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>

Why does this.form.reset() not work when the form is pre-populated with the previously submitted value? The Clear Form button only works before submitting data. I've tried a number of similar approaches using jQuery as well that also only work before submitting the form, never after.

Since JavaScript runs after server-side code, I would expect the value from $_POST['firstname'] to be replaceable with JavaScript (in this case, an empty string).

Upvotes: 0

Views: 1661

Answers (1)

VK321
VK321

Reputation: 5963

As suggested by @Taplar reset will set value which was initially set while page load. Don't get confused with "Reset" form value Vs setting value to "" (Blank string)

Try this:

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 = "";
} 

Upvotes: 2

Related Questions