Search code examples
node-red

How to use onKeypress event in a textbox


I'm currently working with a node-red demo for conversation service,the question is submitted by hitting a send button, I created a function to do the same when the user press "enter" but it does not work... can someone help me to see what is going wrong this is the current code:

  <div id=id_botchathistory>
  </div>
  <div>
      <form>
        <label for="id_chattext">Ask your question here:</label>
        <input type="text" name="chattext" id="id_chattext" onkeypress="javascript:onkeypress()">
        <br/><br/>
      </form>
      <button onclick="javascript:onChatClick()">Send</button>

  function onChatClick() {
    var txt = $('#id_chattext').val();
    chat('You', txt);
    invokeAjax(txt);
  }

  function onkeypress(){
    if (e.keyCode == 13) {
    var txt = $('#id_chattext').val();
    chat('You', txt);
    invokeAjax(txt);
  }
  }

Thanks in advance for all the support.


Solution

  • You have some syntactical mistake and try to use addEventListener for event binding as:

      document.getElementById("id_chattext").addEventListener('keypress', function(e){
     if (e.keyCode == 13) {
        var txt = $('#id_chattext').val();
       e.preventDefault();
       alert(txt);
     }
    });
    

    jsfiddle: https://jsfiddle.net/s9y6qpmv/5/