Problems with Click and Keydown function

0

My problem is that it only works if I click on the button and if I put the keydown then it's time to do a tab on the button and hit enter. I want it to work by clicking the send button and giving enter in the field as the chats. some idea of how to do it.

<form id="mensajeform">
          <input type="text" id="nick" value="<?php echo $_SESSION["nombres"];?>" hidden>
          <input id="mensaje" placeholder="Escribir un mensaje aqui" id="first_name" type="text" class="validate col s11">
          <div id="enviar"  style="background-color:  transparent;border:  transparent;"><img src="views/imagen/enviar.png"></div>
          </form>



$("#enviar").click(function(){

    nick = $("#nick").val();
    mensaje = $("#mensaje").val();

    console.log(nick,mensaje);

    });
    
asked by Alberto Julio Arce Escolar 11.02.2018 в 20:23
source

1 answer

2

Create a function with the functionality to send and invoke it both from the event click of the button and from the keydown of the text box if the key pressed is Enter:

function enviar(){
  nick = $("#nick").val();
  mensaje = $("#mensaje").val();

  console.log(nick,mensaje);
}

$(function(){
  $('#enviar').click(enviar);
  $('#mensaje').keydown(function(e){
    if (e.key === 'Enter') enviar();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="mensajeform">
          <input type="text" id="nick" value="Nick_Usuario" hidden>
          <input id="mensaje" placeholder="Escribir un mensaje aqui" id="first_name" type="text" class="validate col s11">
          <div id="enviar"  style="background-color:  transparent;border:  transparent;"><img src="views/imagen/enviar.png"></div>
</form>
    
answered by 11.02.2018 / 20:32
source