Search code examples
htmlgetsubmitenterpreventdefault

Unable to prevent an input from submitting when press the enter key on it


I'm getting an unexpected behaviour from an input. I have the following code:

<form id="search_form">
    <div id="search_container">
       <input type="text" id="search_text">
    </div>
    <select onchange="search_field_on_change()" name="search_field">
       <option value="login" selected>Usuario</option>
       <option value="su.name">Nombre</option>
       <option value="surnames">Apellidos</option>
       <option value="email">Correo</option>
       <option value="role">Rol</option>
       <option value="access">Acceso</option>
       <option value="center">Centro</option>
    </select>
    <button type="button" onclick="search()">Buscar</button>
    <span id="modify_user_message"></span>
</form>

When I press the enter key on the input element, the form is submitted and the following request is executed:

GET home.php?search_field=login

I want to avoid this behaviour. I've tried it with this:

$('#search_text').keypress(function(e){
    console.log('Hello');
    e.preventDefault();
    if (e.which == 13){
        search();
    }
});

But I don't get anything in the console, so I think the request is performed before the event can be captured.

What can I do?

Thank you.


Solution

  • Try changing your keypress event to keydown because the default behavior of the Enter key is captured on keydown so you have to prevent it at the point where it starts doing its default action.

    Here's a working sample:

          <!DOCTYPE html>
           <html>
           <script>
           function selecting_key(whatKey){
                  if(whatKey.keyCode==13){
             whatKey.preventDefault();
            }
           }
          </script>
         <body>
         <form>
        <input type="text"  onkeydown='selecting_key(event);'>
        </form>
        </body>
        </html>
    

    If you want to check, try changing the onkeydown to onkeyup to know which event can prevent the page from being submitted