How to submit a form by pressing "enter"?

0

How do I make a click type for a input without using a button? For example, I'm going to click on input enter what I want to search for and when you press ENTER the form will be sent. How do I do this with jQuery?

<input type="text" placeholder="Buscar" id="buscar" name="q" />
    
asked by anonymous 19.12.2015 / 02:22

2 answers

3

In the way below it will check if something was written using the regular expression /\w/ , which ignores the whitespace.

Edited example:

$("#buscar").on("blur", function(e) {
  verify(e);
});
$("#buscar").on("keypress", function(e) {
  if (e.keyCode == 13) {
    verify(e);
  }
});

function verify(e) {
  if (!(/\w/.test($("#buscar").val()))) {
    e.preventDefault();
    $('p').html('Preencha algo!');
  } else {
    $('p').html('');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><formaction="">
  <input type="text" id="buscar">
</form>
<p></p>

I used the blur () function that is triggered by the user to take the focus off of input . But if you prefer click , just put .on("click", .

    
19.12.2015 / 02:39
1

You do not need to capture if ENTER was typed in input , because when the enter key is pressed inside an input element on a form, by default the form will be sent.

What you need to do is prevent the form from being sent and you can use event#preventDefault() :

$(function() {
  
  $('#buscar').on('submit', function(event) {
    // Prevenindo a ação padrão (enviar o formulário).
    event.preventDefault();

    // Pegando o valor inserido no input.
    var searchFor = $(this).find('input').val();

    if (!searchFor) {
      alert("Form ñ enviado porque...");
    } else {
      alert("Form enviado.");
      // $(this).submit();
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!--
  - Trocando o '#buscar' para o formulário, ao invés do input.
  -->
<form id='buscar'>
  <input type='search' placeholder='Buscar por...' />
</form>
    
19.12.2015 / 03:26