DForck42
DForck42

Reputation: 20387

Prevent users from submitting a form by hitting Enter

I have a survey on a website, and there seems to be some issues with the users hitting enter (I don't know why) and accidentally submitting the survey (form) without clicking the submit button. Is there a way to prevent this?

I'm using HTML, PHP 5.2.9, and jQuery on the survey.

Upvotes: 1008

Views: 940217

Answers (30)

Dem Pilafian
Dem Pilafian

Reputation: 6026

The unwanted <form> submission happens on the 'keypress' event, so start by creating an event listener for all 'keypress' events:

const blockFormSubmit = (event) =>
   event.key === 'Enter' &&
   event.target.closest('form input') &&
   event.preventDefault();
globalThis.document.addEventListener('keypress', blockFormSubmit);

Then in the listener function check if:

  1. The event keystroke is for the Enter key
  2. The keystroke originated from an <input> tag

Finally, call .preventDefault() on the event so the onsubmit event is not fired.

This strategy of binding a listener higher up in the DOM and then filtering events in the listener is called Event Delegation, and it can be used to simplify event handling.

Upvotes: 0

Nisharg Shah
Nisharg Shah

Reputation: 19662

You can also use javascript:void(0) to prevent form submission.

<form action="javascript:void(0)" method="post">
    <label for="">Search</label>
    <input type="text">
    <button type="submit">Submit</button>
</form>

Upvotes: 15

Jimwel Anobong
Jimwel Anobong

Reputation: 486

Not putting a submit button could do. Just put a script to the input (type=button) or add eventListener if you want it to submit the data in the form.

Rather use this

<input type="button" onclick="event.preventDefault();this.closest('form').submit();">

than using this

<input type="submit">

Note: onclick is needed here to actually submit the form when clicked. By default, type="button" is not sufficient enough to submit.

Upvotes: 15

bdoubleu
bdoubleu

Reputation: 6127

If you're using Alpine, you can use the following to prevent form submission by pressing Enter:

<div x-data>
  <form x-on:keydown.prevent.enter="">...</form>
</div>

Alternatively you can use the .window modifier to register the event listener on the root window object on the page instead of the element.

<form>
  <div x-data>
    <input x-on:keydown.window.prevent.enter="" type="text">
  </div>
</form>

Upvotes: 8

png
png

Reputation: 1130

There are many good answers here already, I just want to contribute something from a UX perspective. Keyboard controls in forms are very important.

The question is how to disable from submission on keypress Enter. Not how to ignore Enter in an entire application. So consider attaching the handler to a form element, not the window.

Disabling Enter for form submission should still allow the following:

  1. Form submission via Enter when submit button is focused.
  2. Form submission when all fields are populated.
  3. Interaction with non-submit buttons via Enter.

This is just boilerplate but it follows all three conditions.

$('form').on('keypress', function(e) {
  // Register keypress on buttons.
  $attr = $(e.target).attr('type');
  $node = e.target.nodeName.toLowerCase();
  if ($attr === 'button' || $attr === 'submit' || $node === 'textarea') {
    return true;
  }

  // Ignore keypress if all fields are not populated.
  if (e.which === 13 && !fieldsArePopulated(this)) {
    return false;
  }
});

Upvotes: 7

Wenfang Du
Wenfang Du

Reputation: 11427

If using Vue, use the following code to prevent users from submitting the form by hitting Enter:

<form @submit.prevent>...</form>

Upvotes: 4

M Ali Imtiaz
M Ali Imtiaz

Reputation: 159

I have use this Code to disable 'ENTER' key press on both input type [text] and input type [password], you can add other too like input type [email] or also can apply on your desired Input type.

$(document).on('keyup keypress', 'form input[type="text"] , input[type="password"]', function(e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            return false;
        }
    });

Upvotes: 6

khn Rzk
khn Rzk

Reputation: 1292

This is the perfect way, You will not be redirected from your page

$('form input').keydown(function (e) {
if (e.keyCode == 13) {
    e.preventDefault();
    return false;
}
});

Upvotes: 10

David Dehghan
David Dehghan

Reputation: 24845

This disables enter key for all the forms on the page and does not prevent enter in textarea.

    // disable form submit with enter

    $('form input:not([type="submit"])').keydown((e) => {
        if (e.keyCode === 13) {
            e.preventDefault();
            return false;
        }
        return true;
    });

Upvotes: 1

Stergios Zg.
Stergios Zg.

Reputation: 662

$(document).on("keydown","form", function(event)
{
   node = event.target.nodeName.toLowerCase();
   type = $(event.target).prop('type').toLowerCase();

   if(node!='textarea' && type!='submit' && (event.keyCode == 13 || event.keyCode == 169))
   {
        event.preventDefault();
        return false;
    }
});

It works perfectly!

Upvotes: 3

Lars Gross
Lars Gross

Reputation: 110

Go into your css and add that to it then will automatically block the submission of your formular as long as you have submit input if you no longer want it you can delete it or type activate and deactivate instead

 input:disabled {
        background: gainsboro;
      }
      input[value]:disabled {
        color: whitesmoke;
      }

Upvotes: 1

Waqar Alamgir
Waqar Alamgir

Reputation: 9978

Using Javascript (without checking any input field):

<script>
window.addEventListener('keydown', function(e) {
    if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
        e.preventDefault();
        return false;
    }
}, true);
</script>

If someone wants to apply this on specific fields, for example input type text:

<script>
window.addEventListener('keydown', function(e) {
    if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
        if (e.target.nodeName == 'INPUT' && e.target.type == 'text') {
            e.preventDefault();
            return false;
        }
    }
}, true);
</script>

This works well in my case.

Upvotes: 2

BalusC
BalusC

Reputation: 1109655

Disallow enter key anywhere

If you don't have a <textarea> in your form, then just add the following to your <form>:

<form ... onkeydown="return event.key != 'Enter';">

Or with jQuery:

$(document).on("keydown", "form", function(event) { 
    return event.key != "Enter";
});

This will cause that every key press inside the form will be checked on the key. If it is not Enter, then it will return true and anything continue as usual. If it is Enter, then it will return false and anything will stop immediately, so the form won't be submitted.

The keydown event is preferred over keyup as the keyup is too late to block form submit. Historically there was also the keypress, but this is deprecated, as is the KeyboardEvent.keyCode. You should use KeyboardEvent.key instead which returns the name of the key being pressed. When Enter is checked, then this would check 13 (normal enter) as well as 108 (numpad enter).

Note that $(window) as suggested in some other answers instead of $(document) doesn't work for keydown/keyup in IE<=8, so that's not a good choice if you're like to cover those poor users as well.

Allow enter key on textareas only

If you have a <textarea> in your form (which of course should accept the Enter key), then add the keydown handler to every individual input element which isn't a <textarea>.

<input ... onkeydown="return event.key != 'Enter';">
<select ... onkeydown="return event.key != 'Enter';">
...

To reduce boilerplate, this is better to be done with jQuery:

$(document).on("keydown", ":input:not(textarea)", function(event) {
    return event.key != "Enter";
});

If you have other event handler functions attached on those input elements, which you'd also like to invoke on enter key for some reason, then only prevent event's default behavior instead of returning false, so it can properly propagate to other handlers.

$(document).on("keydown", ":input:not(textarea)", function(event) {
    if (event.key == "Enter") {
        event.preventDefault();
    }
});

Allow enter key on textareas and submit buttons only

If you'd like to allow enter key on submit buttons <input|button type="submit"> too, then you can always refine the selector as below.

$(document).on("keydown", ":input:not(textarea):not(:submit)", function(event) {
    // ...
});

Note that input[type=text] as suggested in some other answers doesn't cover those HTML5 non-text inputs, so that's not a good selector.

Upvotes: 842

mate.gvo
mate.gvo

Reputation: 1182

ONLY BLOCK SUBMIT but not other, important functionality of enter key, such as creating a new paragraph in a <textarea>:

window.addEventListener('keydown', function(event) {
  //set default value for variable that will hold the status of keypress
  pressedEnter = false;

  //if user pressed enter, set the variable to true
  if (event.keyCode == 13)
    pressedEnter = true;

  //we want forms to disable submit for a tenth of a second only
  setTimeout(function() {
    pressedEnter = false;
  }, 100)

})

//find all forms
var forms = document.getElementsByTagName('form')

//loop through forms
for (i = 0; i < forms.length; i++) {
  //listen to submit event
  forms[i].addEventListener('submit', function(e) {
    //if user just pressed enter, stop the submit event
    if (pressedEnter == true) {
      updateLog('Form prevented from submit.')
      e.preventDefault();
      return false;
    }

    updateLog('Form submitted.')
  })
}

var log = document.getElementById('log')
updateLog = function(msg) {
  log.innerText = msg
}
input,
textarea {
  display: inline-block;
  margin-bottom: 1em;
  border: 1px solid #6f6f6f;
  padding: 5px;
  border-radius: 2px;
  width: 90%;
  font-size: 14px;
}

input[type=submit] {
  background: lightblue;
  color: #fff;
}
<form>
  <p>Sample textarea (try enter key):</p>
  <textarea rows="4">Hit enter, a new line will be added. But the form won't submit</textarea><br/>
  <p>Sample textfield (try enter key):</p>
  <input type="text" placeholder="" />
  <br/>
  <input type="submit" value="Save" />
  <h3 id="log"></h3>
</form>

Upvotes: 5

Upgradingdave
Upgradingdave

Reputation: 13076

I had to catch all three events related to pressing keys in order to prevent the form from being submitted:

    var preventSubmit = function(event) {
        if(event.keyCode == 13) {
            console.log("caught ya!");
            event.preventDefault();
            //event.stopPropagation();
            return false;
        }
    }
    $("#search").keypress(preventSubmit);
    $("#search").keydown(preventSubmit);
    $("#search").keyup(preventSubmit);

You can combine all the above into a nice compact version:

    $('#search').bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13) { e.preventDefault(); }
    });

Upvotes: 70

Daniel Trebbien
Daniel Trebbien

Reputation: 39228

Section 4.10.22.2 Implicit submission of the W3C HTML5 spec says:

A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

Note: Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)

Therefore, a standards-compliant way to disable any implicit submission of the form is to place a disabled submit button as the first submit button in the form:

<form action="...">
  <!-- Prevent implicit submission of the form -->
  <button type="submit" disabled style="display: none" aria-hidden="true"></button>

  <!-- ... -->

  <button type="submit">Submit</button>
</form>

One nice feature of this approach is that it works without JavaScript; whether or not JavaScript is enabled, a standards-conforming web browser is required to prevent implicit form submission.

Upvotes: 320

sparklos
sparklos

Reputation: 462

I can't comment yet, so I'll post a new answer

Accepted answer is ok-ish, but it wasn't stopping submit on numpad enter. At least in current version of Chrome. I had to alter the keycode condition to this, then it works.

if(event.keyCode == 13 || event.keyCode == 169) {...}

Upvotes: 23

Irfan Ashraf
Irfan Ashraf

Reputation: 2460

  1. Do not use type="submit" for inputs or buttons.
  2. Use type="button" and use js [Jquery/angular/etc] to submit form to server.

Upvotes: 8

Developer
Developer

Reputation: 788

It is my solution to reach the goal, it is clean and effective.

$('form').submit(function () {
  if ($(document.activeElement).attr('type') == 'submit')
     return true;
  else return false;
});

Upvotes: 18

Erics
Erics

Reputation: 841

A completely different approach:

  1. The first <button type="submit"> in the form will be activated on pressing Enter.
  2. This is true even if the button is hidden with style="display:none;
  3. The script for that button can return false, which aborts the submission process.
  4. You can still have another <button type=submit> to submit the form. Just return true to cascade the submission.
  5. Pressing Enter while the real submit button is focussed will activate the real submit button.
  6. Pressing Enter inside <textarea> or other form controls will behave as normal.
  7. Pressing Enter inside <input> form controls will trigger the first <button type=submit>, which returns false, and thus nothing happens.

Thus:

<form action="...">
  <!-- insert this next line immediately after the <form> opening tag -->
  <button type=submit onclick="return false;" style="display:none;"></button>

  <!-- everything else follows as normal -->
  <!-- ... -->
  <button type=submit>Submit</button>
</form>

Upvotes: 23

user83632
user83632

Reputation:

You can use a method such as

$(document).ready(function() {
  $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
});

In reading the comments on the original post, to make it more usable and allow people to press Enter if they have completed all the fields:

function validationFunction() {
  $('input').each(function() {
    ...

  }
  if(good) {
    return true;
  }
  return false;
}

$(document).ready(function() {
  $(window).keydown(function(event){
    if( (event.keyCode == 13) && (validationFunction() == false) ) {
      event.preventDefault();
      return false;
    }
  });
});

Upvotes: 1047

Brandon
Brandon

Reputation: 70032

You could make a JavaScript method to check to see if the Enter key was hit, and if it is, to stop the submit.

<script type="text/javascript">
  function noenter() {
  return !(window.event && window.event.keyCode == 13); }
</script>

Just call that on the submit method.

Upvotes: 6

bbmud
bbmud

Reputation: 2688

Instead of preventing users from pressing Enter, which may seem unnatural, you can leave the form as is and add some extra client-side validation: When the survey is not finished the result is not sent to the server and the user gets a nice message telling what needs to be finished to complete the form. If you are using jQuery, try the Validation plugin:

http://docs.jquery.com/Plugins/Validation

This will require more work than catching the Enter button, but surely it will provide a richer user experience.

Upvotes: 22

Eonasdan
Eonasdan

Reputation: 7765

A nice simple little jQuery solution:

$("form").bind("keypress", function (e) {
    if (e.keyCode == 13) {
        return false;
    }
});

Upvotes: 21

Tapas Pal
Tapas Pal

Reputation: 7207

Use:

// Validate your form using the jQuery onsubmit function... It'll really work...

$(document).ready(function(){
   $(#form).submit(e){
       e.preventDefault();
       if(validation())
          document.form1.submit();
   });
});

function validation()
{
   // Your form checking goes here.
}

<form id='form1' method='POST' action=''>
    // Your form data
</form>

Upvotes: -2

Tom Hubbard
Tom Hubbard

Reputation: 16139

If you use a script to do the actual submit, then you can add "return false" line to the onsubmit handler like this:

<form onsubmit="return false;">

Calling submit() on the form from JavaScript will not trigger the event.

Upvotes: 84

edx
edx

Reputation: 1347

I'd like to add a little CoffeeScript code (not field tested):

$ ->
    $(window).bind 'keypress', (event) ->
        if event.keyCode == 13
            unless {'TEXTAREA', 'SELECT'}[event.originalEvent.srcElement.tagName]
                event.preventDefault()

(I hope you like the nice trick in the unless clause.)

Upvotes: 0

goodeye
goodeye

Reputation: 2459

I needed to prevent only specific inputs from submitting, so I used a class selector, to let this be a "global" feature wherever I need it.

<input id="txtEmail" name="txtEmail" class="idNoEnter" .... />

And this jQuery code:

$('.idNoEnter').keydown(function (e) {
  if (e.keyCode == 13) {
    e.preventDefault();
  }
});

Alternatively, if keydown is insufficient:

$('.idNoEnter').on('keypress keydown keyup', function (e) {
   if (e.keyCode == 13) {
     e.preventDefault();
   }
});

Some notes:

Modifying various good answers here, the Enter key seems to work for keydown on all the browsers. For the alternative, I updated bind() to the on() method.

I'm a big fan of class selectors, weighing all the pros and cons and performance discussions. My naming convention is 'idSomething' to indicate jQuery is using it as an id, to separate it from CSS styling.

Upvotes: 7

Buzogany Laszlo
Buzogany Laszlo

Reputation: 941

Use:

$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
  if(e.keyCode == 13) {
    e.preventDefault();
    return false;
  }
});

This solution works on all forms on a website (also on forms inserted with Ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.

Upvotes: 25

Blza Box
Blza Box

Reputation: 345

In my case I had a couple of jQuery UI autocomplete fields and textareas in a form, so I definitely wanted them to accept Enter. So I removed the type="submit" input from a form and added an anchor <a href="" id="btn">Ok</a> instead. Then I styled it as a button and added the following code:

$( '#btn' ).click( function( event ){
    event.preventDefault();
    if ( validateData() ){
        $( 'form#frm' ).append( '<input type="submit" id="frm-submit" style="display:none;"></input>' );
        setTimeout( function(){ $( '#frm-submit' ).click(); }, 500 );
    }
    return false;
});

If a user fills all required fields, validateData() succeeds and the form submits.

Upvotes: -3

Related Questions