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


i'm getting unexpected behaviour input. have 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 press enter key on input element, form submitted , following request executed:

get home.php?search_field=login 

i want avoid behaviour. i've tried this:

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

but don't in console, think request performed before event can captured.

what can do?

thank you.

try changing keypress event keydown because default behavior of enter key captured on keydown have prevent @ point starts doing default action.

here's 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 want check, try changing onkeydown onkeyup know event can prevent page being submitted


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -