how to make an event using the enter key?

3

I would like to know how I can make a system type onclick or click for jQuery.

When the user presses the enter key on a form it automatically clicks the button and sends the form with click .

I know how to do but would like to learn this method as well.

code:

 <script>
        $("#envia").click(function(){
            var campo = {
                nome: $("#nome").val(),
                email: $("#email").val(),
                assunto: $("#assunto").val(),
                message: $("#message").val()
            };

            if(!campo.nome || !campo.assunto || !campo.email || !campo.message){
                $.alert({
                title: 'Atenção',
                content: 'Todos os campos sao obrigatorios!',
                });
                return;
            }

        });
    </script>
    
asked by anonymous 23.09.2015 / 20:09

2 answers

3

You can use this code

$(function(){
    $('input, textarea').on('keypress', function(e){
        if (e.keyCode == 13) {
            e.preventDefault();
            $("#BotaoId").click();
        }
    });
});

If you understand English you have an answer that would also help with javascript pure SO English

Your code should look like this

$(function(){
    $('input, textarea').on('keypress', function(e){
        if (e.keyCode == 13) {
            e.preventDefault();
            $('#envia').click();
        }
    });

    $("#envia").click(function(){
        var campo = {
            nome: $("#nome").val(),
            email: $("#email").val(),
            assunto: $("#assunto").val(),
            message: $("#message").val()
        };

        if(!campo.nome || !campo.assunto || !campo.email || !campo.message){
            $.alert({
            title: 'Atenção',
            content: 'Todos os campos sao obrigatorios!',
            });
            return;
        }

    });
});
    
23.09.2015 / 20:15
3

You can use a delegate event. Delegate in the form but you check to make sure you're sure of what's going to happen and what element you're in. For example:

$('#idDaMinhaForm').on('keyup', function(e){
    if(e.which != 13) return; // não é o "enter"
    if (e.target.tagName.toLowerCase() == 'input') this.submit();
});

Example: link

    
23.09.2015 / 20:16