How do I call a function by pressing Enter in <input>

Asked

Viewed 11,708 times

5

I’m creating a chat for a website and need the user to just press the enter and the message appears on chat, this function works normally with a field textarea but with input nay.

HTML

<form action="" method="post" id="frm-msg">
    <fieldset>
        <label> 
            <input type="text" name="mensagem" id="mensagem" class="textarea" />
        </label> 
    </fieldset>
</form>

Javascript

$(function() {
     //inserir
     $("#submit").click(function() {
         var msg = $("#mensagem").val();
         msg = $.trim(msg);
         if (msg != '') {
             $.post('chat.php', {
                 mensagem: msg,
                 acao: 'inserir'
             }, function(retorno) {
                 $("#painel").prepend(retorno);
                 $("#mensagem").val('');
             });
         }
     });
     //atualizar
     setInterval(function() {
         $.post('chat.php', {
             acao: 'atualizar'
         }, function(retorno) {
             $("#painel").html(retorno);
         });
     }, 5000);
     $(document).keypress(function handleEnter(e, func) {
         if (e.keyCode == 13 || e.which == 13) {
             var msg = $("#mensagem").val();
             msg = $.trim(msg);
             if (msg != '') {
                 $.post('chat.php', {
                     mensagem: msg,
                     acao: 'inserir'
                 }, function(retorno) {
                     $("#painel").prepend(retorno);
                     $("#mensagem").val('');
                 });
             }
         }
     });
 });

4 answers

5

I think something like that:

$(document).on('keydown', function(event) {

    if(event.keyCode === 13) {

        // Sua função aqui

    }

});

3

Click on Enter within an input submits/submits to form, while in the textarea creates a new line.

So the answer to your question goes through what I mentioned above and also through code that "listen" the keyboard and look when the key Enter (that has the code 13) is loaded. Once your input has an ID you can use so:

$('#mensagem').on('keydown', function(event) { // também pode usar keyup
    if(event.keyCode === 13) {
        // Correr código
    }
});

Given the first problem mentioned, you have two options:

#1 Remove the element <input> from within the form.
Example

#2 prevent the sending of form:

An alternative is to prevent directly in HTML

<form onkeypress="return event.keyCode != 13;">

Example

Another is without javascript in html, adding this to your Javascript:

$('#frm-msg').on('submit', function(){
    return false;
});

Example

3

Native Javascript:

document.addEventListener('keydown', function (event) {
    if (event.keyCode !== 13) return;
    // Aqui seu código
}):

jQuery:

$(document).on('keydown', function (event) {
    if (event.keyCode !== 13) return;
    // Aqui seu código
}):

You can replace document by the element of your field, using native querySelector('#idDoElemento') or in the jQuery $('#idDoElemento')

Save the condition that the focus should be on the element or on a child of it.

0

using Jquery is very simple

HTML

<input type="text" id="meuInput" />

Javascript

$('#meuInput').keydown(function(e){
 if (e.which == 13){
   chamaFuncao() // executa o que vc precisar
 }
})

Browser other questions tagged

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