Solution 1 :

I solved the problem, thanks all.

Solve with changing of send_message in:

function send_message(conv,message){
        var div = document.getElementById('content');
        document.getElementById('inputmsg').value = '';
        div.innerHTML += conv + message + "</br>";
    }

Problem :

I have a JS code to send a message to chat:

function send_message(conv, message) {
  $("#content").html(conv + message);
  $(".current-msg").hide();
  $(".current-msg").delay(500).fadeIn();
  $(".current-msg").removeClass("current-msg");
}


document.getElementById('inputmsg').onkeypress = function(e) {
  if (e.keyCode == 13) {
    send_message("TestUser: ", "test message");
  }
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>

<section class="chat">
  <div id="content"></div>
  <div class="formContainer">
    <div class="formDiv" id="chat_form">
      <input type="text" role="form" id="inputmsg" name="inputmsg" style="position: absolute; bottom: 5px; font-family: 'Nunito', sans-serif;" placeholder="Type your message here" class="contact-form" data-toggle="validator" class="shake" />
    </div>
  </div>
</section>

If i put the code to send a test message at the down of this function is working:

send_message("TestUser: ", "test message");

BUT, if i put this code on a function (like enter on input) i don’t get any message (i also tried to make a timer of 5 seconds to send the message):

document.getElementById('inputmsg').onkeypress = function(e) {
            if(e.keyCode == 13) {
                send_message("TestUser: ", "test message");
            }
        }

Comments

Comment posted by MKougiouris

Show us the html part. Maybe you bind the handler before the element “inputmsg” is actually created?

Comment posted by Thos-Host

Done, edited post.

Comment posted by MKougiouris

if you put a console.log statement in the handler, does it get executed?

Comment posted by playcode.io

I tried the same code on

Comment posted by Dave Newton

You should add an answer, but we don’t tag question titles with “solved”—we we just accept an answer

By