How to bind submit button to ENTER KEY

Opeyemi AbdulRasheed
Opeyemi AbdulRasheed used Ask the Experts™
on
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

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Expert of the Year 2008
Top Expert 2008

Commented:
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

@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
Expert of the Year 2008
Top Expert 2008

Commented:
>> 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>

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial