Simple jquey chat with html database - How to send form by pressing the enter key

1

I'm trying to minimize to the maximum how very small I'll post my whole code, I came across a problem the code is working perfectly, but when I click on the send button it works, I'd like to know how to make it work by pressing the enter key or clicking.OBS: I do not handle much of jquery

index.html

 <div id="chat"></div><br />
  <form action="#" method="post">
  <input type="hidden" id="nome" value="<?=$usuario?>" size="6">
  <input type="text" id="mensagem" width="80%" >
  <button type="button" id="enviar" title="enviar" >Enter</button>
  </form>

chat.php

<?php
$nome = $_POST['nome'];
$mensagem = $_POST['mensagem'];
$linha = $nome.' - '.$mensagem.'<br>';
$arquivo = file('chatlog.htm');
array_unshift($arquivo, $linha);
file_put_contents('chatlog.htm', $arquivo);
?>

script

  $(function() {
conversar();
$('#enviar').click(function() {
    var nome = $('#nome').val();
    var mensagem = $('#mensagem').val();
    $.post('chat.php', {'nome':nome, 'mensagem': mensagem }, function() {
      conversar;
    $('#mensagem').val('');
    });
});

function conversar() {
  $('#chat').load('chatlog.htm');
  $('#mensagem').focus();
}
setInterval(conversar, 3000);
});

css

 #chat {
    width: 300px;
    height: 400px;
    border: black 1px solid;
    background-color: #000000;
    overflow-x: hidden;
    overflow-y: scroll; 
    padding: 5px;
    margin-left: 10px;
   }
   fieldset {
    width: 330px;
    background-color: #e6e2af;
    border: black 1px solid;
   }

data is saved in a file named chatlog.htm

    
asked by anonymous 07.02.2016 / 00:23

2 answers

4

A good option is to create a JavaScript function to respond to events of keypress no input where the message is typed:

function enviarEnter(e){
    var tecla=(window.event)?event.keyCode:e.which;
    if (tecla == 13)
    {
        //coloca se o que precisa fazer, ex: função ajax;
    }
}

And in input would look like this:

<input type="text" id="mensagem" onkeypress="enviaEnter(event)"/>

In this way each key pressed will check if the key pressed Enter and if so, it will execute the function.

    
07.02.2016 / 00:34
0
  

About the type attribute of buttons

  • submit: The button sends the form data to the server.
  • button: The button has no default behavior. It may have client-side scripts associated with element events, which are triggered when the event occurs.
  •   

    Use the type submit that the enter key will work!

    <button type="submit" id="enviar" title="enviar" >Enter</button>
    
        
    19.06.2018 / 15:53