How to bind submit button to ENTER KEY

Hello Experts!

Please I want the ENTER KEY to perform the same function as the Submit button in the code below.

I've tried this:
$('.chat_message').keypress(function (e) {
	 var key = e.which;
	 if(key == 13)  // the enter key code
	  {
	    var to_user_id = $(this).attr('id');
        var chat_message = $('#chat_message_'+to_user_id).val();
        if (chat_message == ""){
            toastr.error("Your message is empty");
            return false;
         }
        var to_username = $('#to_username_'+to_user_id).val();
        $.ajax({
            url:"../controllers/insert_chat",
            method:"POST",
            data:{to_username:to_username, to_user_id:to_user_id, chat_message:chat_message},
            success:function(data)
            {
                $('#chat_message_'+to_user_id).val('');
                $('#chat_history_'+to_user_id).html(data);
            }
        })
	    return false;  
	  }
	});

Open in new window

Each time I press ENTER KEY, the page reloads and bootstrap modal disappears.

modal_content += '<input name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" placeholder="Type your message here ..." type="text" class="form-control chat_message" autocomplete="off"><span class="input-group-btn"><button name="send_chat" id="'+to_user_id+'" class="btn btn-sm btn-info no-radius send_chat" type="button"><i class="ace-icon fa fa-share"></i>Send</button></span></div></div>';

Open in new window


AJAX:
$(document).on('click', '.send_chat', function(){
        var to_user_id = $(this).attr('id');
        var chat_message = $('#chat_message_'+to_user_id).val();
        if (chat_message == ""){
            toastr.error("Your message is empty");
            return false;
         }
        var to_username = $('#to_username_'+to_user_id).val();
        $.ajax({
            url:"../../insert_chat",
            method:"POST",
            data:{to_username:to_username, to_user_id:to_user_id, chat_message:chat_message},
            success:function(data)
            {
                $('#chat_message_'+to_user_id).val('');
                $('#chat_history_'+to_user_id).html(data);
            }
        })
    });

Open in new window

LVL 1
Opeyemi AbdulRasheedAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hieloCommented:
The following line:
modal_content += ...

Open in new window

suggests that you are dynamically adding those buttons (typically/most likely after the page has loaded), but this line:
$('.chat_message').keypress(function (e) {...}

Open in new window

suggests that you are trying to bind to the keypress event as the page is loading.  If this is the case, then when you are attempting to bind, the buttons do not exist on the page yet.  

instead of:
$('.chat_message').keypress(function (e) {...});

try binding to the document instead:
$(document).on('keypress','.chat_message',function (e) {...});

On another note, you seem to have copied line 2 from your AJAX code block and pasted it on line 5 of your first code block.  Those are not interchangeable because <input class="chat_message"> has attribute id="chat_message_USERID"; however, <button class="send_chat"> has id="USERID".  So, you need to remove the "chat_message_" prefix from INPUT.chat_message:

var to_user_id = $(this).attr('id').replace('chat_message_','');

Open in new window


Lastly, if the ENTER key is in fact just an alternative to the "Send Chat" button, then both should be POSTing to the same backend script.  If that is the case, rather than duplicating the code on the keypress(), why don't you just trigger the click even on the "Send Chat"?
$(document).on('keypress','input.chat_message',function(event){
  var key = event.which;
  if( key===10 || key===13){
     $('button.send_chat').trigger('click');
  }
return false;
});

Open in new window

lenamtlCommented:
@hielo what key===10 is for I don't think this exist?

The key===13 is correct this is for ENTER key

I'm using this list as reference:
https://keycode.info/
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
hieloCommented:
>> what key===10 is for I don't think this exist?
Sure it does.  Consult your ASCII table.
10 => "new  line" (aka \n)
13 => "carriage return" (aka \r)

>> The key===13 is correct this is for ENTER key
From past experience, I can tell you that I have seen some browsers report 10 for the Enter key (I believe it was on Mac/Safari).  I don't know if all the major browser's have "standardized" the code across all operating systems, but checking for either 10 or 13 gave me cross-browser & cross-OS support.

<SIDENOTE>
Using Chrome on Windows, when I right-click  (on any page) > inspect, and then click on the "Console" tab and then type:

 
console.log( "\n".charCodeAt(0));

Open in new window


I can confirm that \n is in fact ASCII 10.  Likewise,

 
console.log( "\r".charCodeAt(0));

Open in new window


gives you 13.

This is the "incompatibility" that I've seen in the past -- some systems were generating 10 as the "Enter keystroke", while others were using 13.
</SIDENOTE>
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
HTML

From novice to tech pro — start learning today.