0

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).

Anthony
  • 722
  • 1
  • 9
  • 25
  • Resetting form sets it back to what the value="" were when it was created from the markup. – Taplar May 19 '17 at 16:31
  • Use this solution if you want to clear all your inputs: (http://stackoverflow.com/questions/6364289/clear-form-fields-with-jquery) – Mohit Bhardwaj May 19 '17 at 16:32

1 Answers1

1

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 = "";
} 
VK321
  • 5,768
  • 3
  • 44
  • 47