$(document).ready(function(){
var arr = [];
$(document).on('click', '.msg_head', function() {
var chatbox = $(this).parents().attr("rel") ;
$('[rel="'+chatbox+'"] .msg_wrap').slideToggle('slow');
return false;
});
$(document).on('click', '.close', function() {
var chatbox = $(this).parents().parents().attr("rel") ;
$('[rel="'+chatbox+'"]').hide();
arr.splice($.inArray(chatbox, arr), 1);
displayChatBox();
return false;
});
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text() ;
if ($.inArray(userID, arr) != -1)
{
arr.splice($.inArray(userID, arr), 1);
}
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px;z-index: 1000;" id="'+userID+'" rel="'+ userID+'">'+
'<div class="msg_head">'+username +
'<div class="close">x</div> </div>'+
'<div class="msg_wrap"> <div class="msg_body"><div class="msg_push"></div></div>'+
'<div class="msg_footer"><textarea class="msg_input" rows="4" placeholder="Type a message..." style="padding: 8px;" id="'+userID+'"></textarea></div>'+
'<button type="submit" name="submit" id="'+userID+'" class="send_rec"><i class="fa fa-arrow-right"></i></button> </div> </div>' ;
$("body").append(chatPopup);
displayChatBox();
});
$(document).on('keypress', 'textarea' , function(e) {
if (e.keyCode == 13 ) {
var msg = $(this).val();
$(this).val('');
if(msg.trim().length != 0){
var chatbox = $(this).parents().parents().parents().attr("rel") ;
$('<div class="msg-right">'+msg+'</div>').insertBefore('[rel="'+chatbox+'"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
}
});
function displayChatBox(){
i = 270 ;
j = 260;
$.each( arr, function( index, value ) {
if(index < 4){
$('[rel="'+value+'"]').css("right",i);
$('[rel="'+value+'"]').show();
i = i+j;
}
else{
$('[rel="'+value+'"]').hide();
}
});
}
$(document).on("keypress", "button",function(){
friend_id = this.id;
alert(friend_id);
});
});
In this code I have create a chatbox window. Now, what happen when I use the following code as mention below it alert value.
$(document).on("keypress", "textarea",function(){
friend_id = this.id;
alert(friend_id);
});
but when I using
$(document).on("keypress", "button",function(){
friend_id = this.id;
alert(friend_id);
});
nothing will happen when I use keypress
over button I don't know why? What is the problem with button
? So, How can I get value in alert box when keypress
on button? Please help me.
Thank You
After gaining more information from OP in the comments, it became clear that he wants to alert the userID
and the textarea value when the Enter key is pressed inside the textarea. One approach to achieve this would be:
// Event handler on textareas
$('textarea').on("keypress", function (e) {
// Detect Enter key pressed
if(e.which === 13){
// Get the userID
let friend_id = this.id;
// Get the textarea value
let txt_val = this.value;
// Alert the data
alert('userID: '+friend_id+' Textarea Value: '+txt_val);
}
});