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()?

0

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I actually did this now but reduced the scope to the input fields in the form.
Simon, do I change my answer accordingly?
Simon, are you fine with the answer? Then it should be ready for the acceptance :)
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();
});

2 Comments

Use which instead of keyCode in order to always work properly, since it is a jQuery standardization: api.jquery.com/category/events/event-object
Simon, it will works fine for all the inputs. Have a look at my fiddle jsfiddle.net/Mazzu/hY93D/40 for the same
1

You can use the novalidate attribute in your form element:

<form method="post" action="..." novalidate>...</form>

1 Comment

Thanks, however, I want to validate, but not on ENTER
-2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.