rauchg / chat-example

797 stars 2.05k forks source link

Form submission not stopped (OSX + Chrome) #9

Open dsiah opened 9 years ago

dsiah commented 9 years ago

Hi, I was programming the index.html page and I ran across an error where the return false in the $('form').submit(callback) did not actually stop the callback seen in this block:

$('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
});

For anyone else hitting this problem I remedied it by creating a helper method and attaching it to the button. Instead of using a form element I wrapped the "form" in a div element. the code below is what worked for me to complete the example:


<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      div { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      div input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      div button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script>
      var socket = io();

     // new code replacing the $('form').submit(...) bit
      function pushMessage () {
        var mess = $('#m').val();
        $('#m').val('');
        socket.emit('chat message', mess);
      }

      socket.on('chat message', function (msg) {
        $('#messages').append($('<li>').text(msg));
      });

    </script>
  </head>
  <body>
    <ul id="messages"></ul>
    <div>
      <input id="m" autocomplete="off" />
      <button onclick="pushMessage()">Send</button>
    </div>
  </body>
</html>
jlouthan commented 9 years ago

I was having this issue too. Then realized I just needed to move script tags to the bottom, right before </body>. After doing that, the original chat example code works fine.

adovbos commented 9 years ago

just write $(document).ready(function () { $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); }) where we adding document ready function... now we can put script in head) hope helps)