Ad

Issue With Editing Input Via Websockets By Two Users

I was trying to implement feature of working with same input field with two users using socket.io
Idea looks like this:

  1. User enters data
  2. Data goes to backend
  3. Backend broadcast data across all connected clients

But when I tried to enter a single char - whole input value somehow was set to "" (literally nothing) Maybe I should handle data flow in another way ?

Client code to send data to backend and acquire it on response:

    $('input').keydown(function(){
       socket.emit('chat message', $('input').val());
       console.log($('input').val());
       return false;
    });
    socket.on('chat message', function(msg){
      $('input').val(msg);
    });

Backend code which only used to broadcast data across all conected clients:

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

GitHub repo link: https://github.com/eko24/websocket-input

Ad

Answer

The value of the <input> tag has not yet been changed when the keydown event is fired so you're not seeing the effect of the key that was just pressed.

Instead, you can use the "input" event which signifies when the <input> value has been changed by the user:

$("input").on("input", function(e) {
    log($("input").val());
});

function log(x) {
    var div = document.createElement("div");
    div.innerHTML = x;
    document.body.appendChild(div);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input>

Ad
source: stackoverflow.com
Ad