我正在尝试创建一个网站,如果用户选择其中一个单选按钮,它将打印出他们为连接到服务器的两个人选择的那个单选按钮的值。我已经有一个聊天室部分,一个人可以发送消息,并且两个人都可以同时看到它。我在尝试获取单选按钮的值以同时显示在两个网页上时遇到了一个实际问题。如果有人从单选按钮中选择某项,那么双方都可以看到该单选按钮的输出值,我希望得到它。我已经实现了用于实时更新的Web套接字。
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];
server.listen(process.env.PORT || 3000);
console.log('Server running...');
app.get('/', function(req,res){
res.sendFile(__dirname+ '/index.html');
});
io.sockets.on('connection', function(socket){
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
//disconnect
socket.on('disconnect',function(data){
connections.splice(connections.indexOf(socket),1);
console.log('Disconnected: %s sockets connected', connections.length);
});
//sendmessage
socket.on('send message', function(data){
console.log(data);
io.sockets.emit('new message',{msg: data});
});
//showchecked
socket.on('send checked', function(data){
console.log(data);
io.sockets.emit('new checked',{msg: data});
});
});
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div class="container">
<div class="chat" id="chat"></div>
<form id="messageForm">
<label>Enter Message </label>
<textarea class="form-control" id="message"></textarea>
<br/>
<input type="submit" class="btn btn-primary" value = "Send Message" />
</form>
<div id="checkbox" class="checkbox"></div>
<form id="checkboxForm">
<input type="radio" name="sample" ID="rdnNumber1" value="1" /> Number 1<br/>
<input type="radio" name="sample" ID="rdnNumber2" value="2" /> Number 2 <br/>
<input type="radio" name="sample" ID="rdnNumber3" value="3" /> Number 3
<br/>
<br/>
<input type="button" id="btnGetValue" Value="Get Value" />
<p></p>
</form>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$(function(){
var socket = io.connect();
var $messageForm = $('#messageForm');
var $message = $('#message');
var $chat = $('#chat');
var $checkboxForm = $('#checkboxForm');
var $checkbox1 = $('#checkbox1');
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $message.val());
$message.val('');
});
socket.on('new message', function(data){
$chat.append('<div class="chat">'+data.msg+'</div>');
});
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send checked', $message.val());
$message.val('');
});
socket.on('new checkbox', function(data){
$('#btnGetValue').click(function() {
var selValue = $('input[name=sample]:checked').attr('id');
$('p').html('<br/>Selected Radio Button ID is : <b>' + selValue + '</b>');
});
});
});
</script>
CSS
body {
margin-top:30px;
}