Reputation: 73
I've this code which I'm using to post a message on 'Enter' key press, but it's going on loop and instead of posting one message it's posting it multiple times randomly.
This is the function I'm calling in on <input id='txtsendmsg" + i + "' placeholder=\"Write a comment...\" onkeypress='PostMessage(event,"+i+");' class='msgtxt'></input>
any help would be appreciated.
function PostMessage(event,key) {
$('#txtsendmsg'+key).on("keypress", function (e) {
if (e.which == 13) {
var msgid = $(this).siblings('.msgid').val();
var msgtxt = $(this).val();
$.ajax({
url: "student_post_login.aspx/funPostMessage",
data: 'postd=' + "Y" + '&msgid=' + msgid + '&msgtxt=' + msgtxt,
success: function (data) {
if (data) {
displayData();
}
},
failure: function (response) {
alert("Faliure:");
},
error: function (response) {
alert(response);
}
});
e.preventDefault();
}
});
}
Upvotes: 0
Views: 74
Reputation: 337656
The problem is because you are attaching an event handler every time you hit the a key in the input field. Press a key twice and you get two requests sent, three times; three and so on.
Try assigning the handler using jQuery only instead of the onclick
attribute:
<input id='txtsendmsg" + i + "' placeholder=\"Write a comment...\" class='msgtxt' />
$('.msgtxt').on('keypress', function (e) {
var $el = $(this);
if (e.which == 13) {
var msgid = $el.siblings('.msgid').val();
var msgtxt = $el.val();
$.ajax({
url: "student_post_login.aspx/funPostMessage",
data: 'postd=' + "Y" + '&msgid=' + msgid + '&msgtxt=' + msgtxt,
success: function (data) {
if (data) {
displayData();
}
},
failure: function (response) {
alert("Faliure:");
},
error: function (response) {
alert(response);
}
});
e.preventDefault();
}
});
Upvotes: 5