can't submit form in node js tutorial

- 1 answer


I am doing this

I am on the section Emitting events

When I type a message in the text box and hit send it refreshes the page and takes me to the url localhost:3000/? instead of logging the message on the server.

Why is the button failing to trigger the $('form').submit(function(){ line?

If I open the JS console on chrome and enter

socket.emit("chat message", 'testing from console')

it logs the message in my commandline server window as expected. So I do not think there is an error in the server side code.

I had hand typed out everything but when it wasn't working I copy pasted to make sure I had it right.

So index.html for me is

<!doctype html>
    <title>Socket.IO chat</title>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form 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; }
    <script src=""></script>
    <script src=""></script>
      var socket = io();
        socket.emit('chat message', $('#m').val());
        return false;
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>

and index.js is

var app = require('express')();
var http = require('http').Server(app);
var io = require('')(http)

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    console.log('message: ' + msg);

http.listen(3000, function(){
    console.log('listneing on *:3000')

using chrome Version 47.0.2526.80 (64-bit)




Try wrapping your code in a document ready block. The form may not exist yet.

           socket.emit('chat message', $('#m').val());
           return false;