I'm currently making a web-based chat system but I've run into a problem. I have set up a function in javascript to check if the user presses enter in the textarea and send the message if this has happened. The problem is every time that function is used the textarea is left with a single carriage return in it as if the value of the textarea was "\n" when it should be just "". Here's the code:
function checkEnter(e) {
var charCode;
if (e && e.which) {
charCode = e.which;
} else {
charCode = e.keyCode;
}
if (charCode == 13) {
say();
document.getElementById('chatfieldbox').value = "";
return false;
} else {
return true;
}
}
function say() {
updateStats();
text = document.getElementById('chatfieldbox').value;
xhr=new XMLHttpRequest();
xhr.open("POST", "say", false);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", text.length);
xhr.setRequestHeader("Connection", "close");
xhr.send("text=" + text);
document.getElementById('chatfieldbox').value = "";
update();
}
function updateStats() {
var text = document.getElementById('chatfieldbox').value;
var num = text.length;
var lines = 1;
for (var i = 0; i < num; i++) {
if (text.charAt(i) == '\n') {
lines++;
}
}
document.getElementById('characters').innerHTML = num;
document.getElementById('lines').innerHTML = lines;
}
say(); does some ajax stuff to send the message. updateStats(); is just a character and line counter for the user's benefit. say(); sends the message to the server then calls to update to see if there are messages from anyone else to display (irrelevant). The HTML:
<textarea id="chatfieldbox" onKeyPress="checkEnter(event)"></textarea>
Any suggestions?