简体   繁体   中英

How to pass form input value into variable in socket.emit parms

I want to pass the username input from the form into socket.emit params . However when I step into socket.on function , userName is undefined. It should be the scope issue, while I don't know how to fix that. I omitted some of the codes to simplify the problem. It's not necessary to make the code runable, I just want to get the method how to deal with this problem.

 $("button").click(function (event) { event.preventDefault(); setUserName($("input[name=name]").val()); }); var userName; function setUserName(userName2) { userName=userName2; } var socket = io(); socket.on('connect', function () { var params = { name:userName } socket.emit('join', params, function (err) { }); }); 
 <body class="centered-form"> <div class="centered-form__form"> <form> <div class="form-field"> <label>Display name</label> <input type="text" name="name" autofocus/> </div> <div class="form-field"> <button id="submit">Submit</button> </div> </form> </div> </body> <script src="/libs/jquery-3.1.0.min.js"></script> <script src="/chat.js"></script> 

You have a scoping issue with userName

 $("button").click(function (event) { event.preventDefault(); setUserName($("input[name=name]").val()); }); var userName; function setUserName(userName) { //this refers to the scope of the function this.userName=userName; } var socket = io(); socket.on('connect', function () { var params = { //this refers to the scope of the socket name:this.userName } socket.emit('join', params, function (err) { }); }); 

Try

 $("button").click(function (event) { console.log('__BUTTON_EVENT__'); event.preventDefault(); let name = $("input[name=name]").val(); console.log('__USER_NAME__: ', name); setUserName(name); }); var userName; function setUserName(name) { userName = name; } var socket = io(); socket.on('connect', function () { var params = { name:userName } console.log('__CONNECTING__: ', params.name); socket.emit('join', params, function (err) { }); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM