2
<form ... onsubmit="return false">
   <input type="text" name="location" ...>
   <input type="url" ... required>
   ...
</form>

Now, if I enter a location and hit ENTER, the browser tells me that an URL is required which is not an expected or desired outcome. The ENTER should just be ignored.


Question

How can I prevent the browser from checking the required field after hitting ENTER in the "location" input field and only let the browser check the "url" field when submitting the form with JavaScript using form.submit()?

Mazzu
  • 2,799
  • 20
  • 30
Simon Ferndriger
  • 4,455
  • 6
  • 28
  • 53

4 Answers4

2

You need to stop the default behavior of enter button for your form elements.

Lets have an example:

HTML5 form as

<form id="form">
  <input type="text" name="test1" id="test1" required/>
  <input type="text" name="test2" id="test2" required/>
  <input type="submit" value="Test"/>
</form>

Then apply below code

$(document).ready(function() {
  $(form).find('input').on('keydown', function(e){
     if(e.which == 13) // KEY.ENTER = 13
       e.preventDefault();
  });
});

Based on above scenario, here is the fiddle.

Mazzu
  • 2,799
  • 20
  • 30
1

You can use the novalidate attribute in your form element:

<form method="post" action="..." novalidate>...</form>
Pawel Veselov
  • 3,996
  • 7
  • 44
  • 62
José Barbosa
  • 913
  • 8
  • 17
1

This is what I did now and what worked (using jQuery, where $form represents the ):

$form.find('input').on('keydown', function(e){
    if(e.which == KEY.ENTER) // KEY.ENTER = 13
        e.preventDefault();
});
Simon Ferndriger
  • 4,455
  • 6
  • 28
  • 53
  • Use `which` instead of `keyCode` in order to always work properly, since it is a jQuery standardization: http://api.jquery.com/category/events/event-object/ – Simon Ferndriger Mar 05 '14 at 14:48
  • Simon, it will works fine for all the inputs. Have a look at my fiddle http://jsfiddle.net/Mazzu/hY93D/40/ for the same – Mazzu Mar 05 '14 at 14:54
-2

There is a specific method for handle a "submit". Here's here!

Machado
  • 7
  • 2