Jquery Keeps Posting An Extra Message Each Time I Click Submit
My jQuery code is acting really weird. It keeps posting an extra copy of the same message each time I click on submit. For example: Hello 3 Hello 3 Hello 3 Hello 2 Hello 2 Hello
Solution 1:
This function here registers an event handler every time it's called. Because you're calling it in the click event, every time you click, you register a new event handler. These are managed in a queue, and thus, it will run through the event handler an extra time with each button click.
socket.on('new message', function (data) {
$chat.prepend(data + "<br/>");
});
The solution is to move it outside of the click event.
jQuery(function ($) {
var socket = io.connect();
var$messageForm = $('#sendmessage');
var$messageTitle = $('#title');
var$messageBox = $('#message');
var$chat = $('#chat');
$messageForm.click(function (e) {
if ($.trim($("#title").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
returnfalse;
}
if ($.trim($("#message").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
returnfalse;
} else {
e.preventDefault();
socket.emit('send message', '<b>' + $messageTitle.val() + '</b>' + ' - ' + $messageBox.val());
$messageTitle.val('');
$messageBox.val('');
}
});
socket.on('new message', function (data) {
$chat.prepend(data + "<br/>");
});
});
Post a Comment for "Jquery Keeps Posting An Extra Message Each Time I Click Submit"