lock enter inside an input

Asked

Viewed 6,169 times

3

Guys I have the following input inside a form:

<input type='text' class='form_campos form_campos_nome' id='auto' name='verifica_nome3'>

I need to block the enter key inside it, that is, when the cursor is inside it enter does not send the form, but if it is inside any other input enter can send the form.

Someone knows how to do it?

3 answers

3

You can add a function to your input that does nothing when enter is pressed.

<input type='text' class='form_campos form_campos_nome' id='auto' name='verifica_nome3' onkeypress="doNothing()">

function doNothing() {  
  var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
  if( keyCode == 13 ) {


  if(!e) var e = window.event;

  e.cancelBubble = true;
  e.returnValue = false;

  if (e.stopPropagation) {
    e.stopPropagation();
    e.preventDefault();
  }
} 

1


Use the event for all inputs but excludes that:

$('input').not('#auto').keypress(function(e) {
    if(e.which == 13) { // se pressionar enter
        console.log('pode submeter'); // aqui pode submeter o form
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='form_campos form_campos_nome' id='auto' name='verifica_nome3'>
<input type="text" placeholder="Se o cursor estiver aqui pode submeter form">

EXAMPLE in jsfiddle

Or the other way around (probably this one fits more with what you want):

$('#auto').keypress(function(e) {
    if(e.which == 13) {
      e.preventDefault();
      console.log('Não vou enviar');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type='text' class='form_campos form_campos_nome' id='auto' name='verifica_nome3'>
<input type="text" placeholder="Se o cursor estiver aqui pode submeter form">
<input type="submit">
</form>

EXAMPLE in jsfiddle

1

if it’s just to lock enter, just do this:

$(function() {
   $('form').submit(function(event){
       return checkFocus();
    });
 });

 function checkFocus() {
  if ($('#auto').is(':focus')) {
     return false;
  }
  return true;
 }

Here the working example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.