I designed a single-page small application, a mini chat room.
As soon as you enter, there is a black screen, and then there is a small panel where you need to enter your name. There is a button next to it to confirm (the first keypress). After confirmation, the black screen and the panel disappear and you enter the page.
The page is a chat room, which triggers the press Enter to send a message (the second keypress).
The problem now is that when entering the name panel, pressing Enter will trigger both keypresses above at the same time. But the selectors bound to my two keypresses are different.
P.S. In html, the type of both buttons is button.
Please give me an answer, thank you very much.
Code:
//get username
function getUsername(){
blackScreen.fadeOut("slow");
return $("#input-username").val();
}
okay.click(getUsername);
//send msg to database by enter
formUsername.keypress(function(event) {
if(event.keyCode === 13) {
event.preventDefault();
okay.trigger("click");
}
});
//get time
function getTime() {
var mydate = new Date();
var year = mydate.getFullYear();
var month = mydate.getMonth() + 1;
var day = mydate.getDate();
var hour = mydate.getHours();
var minute = mydate.getMinutes();
var second = mydate.getSeconds();
//standardize time
function stdTime(s) {
if(s < 10) {
return "0" + s;
} else {
return s;
}
};
return year + "/" + stdTime(month) + "/" + stdTime(day) + " " + stdTime(hour) + ":" + stdTime(minute) + ":" + stdTime(second);
}
//send msg to database by click
inputBtn.click(function() {
var inputMsg = $("#input-value").val();
//push msg to database
msgs.push({
"name": getUsername(),
"time": getTime(),
"msg": inputMsg
});
$("#input-value").val("");
});
//send msg to database by enter
inputForm.keypress(function(event) {
if(event.keyCode === 13) {
event.preventDefault();
inputBtn.trigger("click");
}
});
Add the code for the two button parts of html:
<p class="chat-room-input">
<form class="form-inline form-input">
<p class="form-group">
<input type="text" class="form-control" id="input-value" placeholder="来一起吐槽~" maxlength="80">
<button type="button" class="btn btn-default" id="input-send">
<span class="glyphicon glyphicon-send" aria-hidden="true"></span>
</button>
</p>
</form>
</p>
<p class="alert alert-warning alert-dismissible" role="alert">
<form class="form-inline form-username">
<p class="form-group">
<input type="text" class="form-control" id="input-username" placeholder="骚年!留下大名!" maxlength="10" autofocus="autofocus">
<button type="button" class="btn btn-default okay">OK</button>
</p>
</form>
</p>
Done, thank you for your answer.