Reputation: 1263
I have a form. The only way I want the form to be submitted is with the submit button. I want to ensure that the enter button or go button on ios were not used to submit the form.
Upvotes: 0
Views: 245
Reputation: 541
The <input type="button">
will not trigger an automatic submit with the enter key or the 'go' button on mobile devices.
<form action="my-handler.php" method="POST" id="my_form">
<label for="some_input">Input 1
<input name="some_input" id="some_input" type="text">
</label>
<label for="another_input">Input 2
<input name="another_input" id="another_input" type="text">
</label>
<input type="button" value="Submit Form" id="submit_button">
</form>
<script type="text/javascript">
// Stop the form from submitting if enter is pressed
// or the 'go' button is pressed on mobile
$( '#my_form' ).submit(function(e) {
e.preventDefault();
});
// Submit the form when button is clicked
$( document ).on( 'click', '#submit_button', function() {
$( '#my_form' ).submit();
});
</script>
You should probably not focus so much on preventing form submission with enter or 'go' on mobile, as this will degrade user experience. I imagine you're doing this because there is something that would be easy to trigger the submission before the form is finished being filled out. Perhaps, in this event form validation is a better friend to you, with something like this:
<script type="text/javascript">
$( '#my_form' ).submit( function(e) {
e.preventDefault(); // Don't let the form submit yet
if( true == validateForm() ) {
$( '#my_form' ).submit(); // Submit the form
} else {
// Show error output
}
});
// Validation function - returns true or false
function validateForm() {
// Do all your field validation and return
return true;
}
</script>
Upvotes: 1
Reputation: 724
Use the button type as button and assign it onclick function
<script type="text/javascript">
function submitform(){
$('#myform').submit();
}
</script>
<form id="myform" name="myform" action="somepage" method="POST">
<button type="button" onclick="submitform();"></button>
</form>
Upvotes: 1