Reputation: 3
I want to write a little chat. On the first load of the page old messages and answers will be loaded from the database. So I have many messages with different IDs. For every message I have a link to reply. When you click on it a message box appears. My problem is, that I want to send the reply when the user press Enter on his keyboard.
The reply textareas are added with jquery so I can't use $(textarea).keypress(.....)
Here is a example of my code:
<div id="container" style="">
<div id="main" role="main">
<div id="shoutbox_container">
<div id="shoutbox_content" style="margin-top:20px;"></div>
</div>
</div>
for (id = 0; id < 5; id++) {
var res_container = '<div id="shoutbox_entry_' + id + '" class="entry entrybox">';
res_container += 'Mr Idontknow wrote:' + id + '. Message ';
res_container += ' <span class="reply" id="reply" data-parentid="' + id + '">reply</span> ';
res_container += '<div class="replytextbox replybox" id="reply_textbox_' + id + '" style="display:none;">';
res_container += '<textarea class="replytext" name="antwort" id="antwort_' + id + '" data-parentid="' + id + '"></textarea>';
res_container += '<button id="replysend">send</button> ';
res_container += '</div>';
res_container += '</div><br><br>';
$('#shoutbox_content').prepend(res_container); }
//reply textarea
$('#shoutbox_content').on('click', '#reply', function () {
var parentid = $(this).data('parentid');
$('#shoutbox_content').find('#reply_textbox_' + parentid).toggle();
});
//reply send button
$('#shoutbox_content').on('click', 'button', function () {
var parentid = $(this).prev('textarea').data('parentid');
var reply = $(this).prev('textarea').val();
$(this).prev('textarea').val('');
$('#shoutbox_content').find('#reply_textbox_' + parentid).hide();
if (reply.length > 0) {
alert('save reply ' + parentid);
}
});
// when the client hits ENTER on their keyboard
$('#shoutbox_content').keypress('textarea', function (e) {
if (e.which == 13) {
console.log($(this).find('textarea'));
var test = $(this).attr('data-parentid');
alert('Enter ' + test);
$(this).blur();
$(this).next('#replysend').focus().click();
}
});
It works but I don't know which ID was send. Has anybody an idea how I can find out in which reply textarea the user pressed Enter?
Upvotes: 0
Views: 9101
Reputation: 14025
So, use .on() function like others events declaration you are using :
// when the client hits ENTER on their keyboard
$('#shoutbox_content').on('keypress','textarea', function (e) {
//Retrieve ID of the textarea
var id = $(this).attr('id');
//Do what you want with id variable
if (e.which == 13) {
console.log($(this).find('textarea'));
var test = $(this).attr('data-parentid');
alert('Enter ' + test);
$(this).blur();
$(this).next('#replysend').focus().click();
}
});
Then retrieve the textarea where the event occurred by checking its ID or another attribute like this : $(this).attr('id')
Upvotes: 4