I am a JavaScript newbie. I have an input text field that I wish to clear after pressing the form submit button. How would I do that?
A:
In your FORM element, you need to override the onsubmit
event with a JavaScript function and return true.
<script type="text/javascript">
function onFormSubmit ()
{
document.myform.someInput.value = "";
return true; // allow form submission to continue
}
</script>
<form name="myform" method="post" action="someaction.php" onsubmit="return onFormSubmit()">
<!-- form elements -->
</form>
Nick Bedford
2009-09-29 05:52:44
Uh oh... won't this have the effect of the server-side handling this POST to not see anything in the corresponding form field ?
mjv
2009-09-29 05:54:37
Could do. I must admit, I've never done this. I would have expect the POST data to be rounded up before continuing.
Nick Bedford
2009-09-29 22:06:12
+1
A:
If a user presses the submitbutton on a form the data will be submitted to the script given in the action attribute of the form. This means that the user navigates away from the site. After a refresh (assuming that the action of the form is the same as the source) the input field will be empty (given that it was empty in the first place).
If you are submitting the data through javascript and are not reloading the page, make sure that you execute Nick's code after you've submitted the data.
Hope this is clear (although I doubt it, my English is quite bad sometimes)..
Lex
2009-09-29 07:36:36