javascript - jQuery keeps posting an extra message each time I click submit -
my jquery code acting weird. keeps posting copy of same message each time click on submit. example:
hello 3 hello 3 hello 3 hello 2 hello 2 hello
anyone have idea why happening? here code far:
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(''); return false; } if ($.trim($("#message").val()).length === 0) { alert('you must provide valid input'); $messagetitle.val(''); $messagebox.val(''); return false; } 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/>"); }); }); });
this function here registers event handler every time it's called. because you're calling in click event, every time click, register new event handler. these managed in queue, , thus, run through event handler time each button click.
socket.on('new message', function (data) { $chat.prepend(data + "<br/>"); });
the solution move outside of 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(''); return false; } if ($.trim($("#message").val()).length === 0) { alert('you must provide valid input'); $messagetitle.val(''); $messagebox.val(''); return false; } 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/>"); }); });
Comments
Post a Comment