Thursday, March 28, 2013

Disable Enter Key from Submit on Forms

Know:
Forms, Javascript, patience.

NOTHING and I mean NOTHING has frustrated me more than this annoyance.

By default, ALL forms treat <ENTER> the same as clicking a button.  This means the moment you press enter the form is submitted.  What, but what if I have a form with multiple fields and every one needs to be entered BEFORE submission.
Sure, you could disable the enter key but wow, that's fun for the user.  Pressing tab and not enter gets old REAL FAST.  So...what do I do.

Step 1:
Disable the form.

This is pretty easy and requires NO coding.

<Form id='myform' name='myform action='dosomething.php' >

Nothing special but we need to stop submit.  We will add ONE line.

onsubmit='return false'

Now...

<form id='myform' name='myform' action='dosomething.php' onsubmit='return false'>

This essentially is taking advantage of Javascript.  If you want to hook up an event to onsubmit you can do that.  Returning false will keep you in the form.  This is great for validating text, etc.  For now though, we're just going to return false.  OH NO.  Now I will NEVER have the form submit right?

WRONG!!!!

This is the key.
Create a button that will submit the form.  We're going to add a PAINLESS function in Javascript to submit the form.  Really, it's quick.

First the function.  You can either add it to the top of your html, OR, add it to your javascript library.  For this example, we'll just add it to a script.

<script>
function SubmitForm ('IdOfForm')  // that's the ID of the form.  Handy for submitting
{
    var SelectedForm = document.getElementById (IDOfForm);
     SelectedForm.submit ();

}

</script>

OK so now you have the script.  BUT WAIT???? Where do I put it?  Well an easy solution is with a button.

<!-- this is all one line but is wrapping on this blogspot --!>
<input type='button' class='your class (optional) value='Save' onsubmit='SubmitForm(this.id); return false;"></input>

The return false is VERY important.  Take it out and you'll have the return key submitting your form.  Try it.  Works great for me and have fun.

No comments:

Post a Comment