简体   繁体   English

输入键时获取输入文本的值

[英]get the value of input text when enter key

how i can get the value of input text when enter key pressed in this cod ?在此 cod 中按下 Enter 键时,如何获取输入文本的值? ..................................................................... ………………………………………………………………………………………………………………………………………………………… ……………………

<body>
  <div id="center">
    <div id="boxtop"></div> 

    <div id="boxdown"> 
      <input type="text" id="txt"/>
      <button type="submit"  onclick="SaveData()" id="btn" >SEND</button>
    </div> 

  </div> 
  <script>
    function SaveData() {
        work = "insert";
        chat = $('#txt').val();
        $.ajax({
            type: "POST",
            url: "server.php",
            data: "work="+work+"&chat="+chat,
            success: function(msg){
                 $('#txt').val('');
                }
            });
        }
  </script>
</body>

You should add a form around your button and input.您应该在按钮和输入周围添加一个表单。 Then you can handle both events with然后你可以处理这两个事件

$('form').on('submit', function() {
    SaveData();
    return false;
});

If you want to fire an event with ajax function you do not need submit button.如果要使用 ajax 函数触发事件,则不需要提交按钮。

$('form').on('submit', function(){
   preventDefault(); ....

Why you submit the form and then prevent submit?为什么你提交表单然后阻止提交?

It is better to do this:最好这样做:

   $(document).keydown(function (e)
    {
        if(e.keyCode == 13)
          SaveData();
    });
  $('#txt').keypress(function (e) {
      if(e.which == 13) {
          chat = $('#txt').val();
      }
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM