-1

how i can get the value of input text when enter key pressed in this cod ? .....................................................................

<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>
Toprex
  • 155
  • 1
  • 9
  • Possible duplicate of [get the value of input text when enter key pressed](http://stackoverflow.com/questions/20998541/get-the-value-of-input-text-when-enter-key-pressed) – gzc Jan 27 '17 at 05:28

3 Answers3

1

You should add a form around your button and input. Then you can handle both events with

$('form').on('submit', function() {
    SaveData();
    return false;
});
pixelarbeit
  • 484
  • 2
  • 11
0

If you want to fire an event with ajax function you do not need submit button.

$('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();
    });
Farzin Kanzi
  • 3,380
  • 2
  • 21
  • 23
0
  $('#txt').keypress(function (e) {
      if(e.which == 13) {
          chat = $('#txt').val();
      }
  });
xlm
  • 6,854
  • 14
  • 53
  • 55
sohel101091
  • 235
  • 1
  • 2
  • 10