I am looking for the neatest way to create an HTML form which does not have a submit button. That itself is easy enough, but I also need to stop the form from reloading itself when submission-like things are done (for example, hitting Enter in a text field).
7 Answers
Simply add this event to your text field. It will prevent a submission on pressing Enter, and you're free to add a submit button or call form.submit() as required:
onKeyPress="if (event.which == 13) return false;"
For example:
<input id="txt" type="text" onKeyPress="if (event.which == 13) return false;"></input>
an idea:
<form method="POST" action="javascript:void(0);" onSubmit="CheckPassword()">
<input id="pwset" type="text" size="20" name='pwuser'><br><br>
<button type="button" onclick="CheckPassword()">Next</button>
</form>
and
<script type="text/javascript">
$("#pwset").focus();
function CheckPassword()
{
inputtxt = $("#pwset").val();
//and now your code
$("#div1").load("next.php #div2");
return false;
}
</script>
The first response is the best solution:
Add an onsubmit handler to the form (either via plain js or jquery $().submit(fn)), and return false unless your specific conditions are met.
More specific with jquery:
$('#your-form-id').submit(function(){return false;});
Unless you don't want the form to submit, ever - in which case, why not just leave out the 'action' attribute on the form element?
Writing Chrome extensions is an example of where you might have a form for user input, but you don't want it to submit. If you use action="javascript:void(0);", the code will probably work but you will end up with this problem where you get an error about running inline Javascript.
If you leave out the action completely, the form will reload which is also undesired in some cases when writing a Chrome extension. Or if you had a webpage with some sort of an embedded calculator, where the user would provide some input and click "Calculate" or something like that.