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:
- User enters data
- Data goes to backend
- 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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad