mercredi 1 juillet 2015

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.

Aucun commentaire:

Enregistrer un commentaire