Facebook Style Press Enter to Send Option in Message / Comment Box using jQuery

Hi guys, Today I am going to tell you how to create Press Enter to Send option in comment or message box using jQuery.

I would say it is one of the best feature where you can submit a form by clicking a button or just pressing the enter key.

Facebook already has this feature in Messaging system. So I thought it will be very useful for web developers who really doing cool things in User Interface.

Press Enter to Send in jQuery

Contents

jQuery Code to show/hide post button

$('#press_to_enter').click(function() {
var checkedValue = $('#press_to_enter:checked').val();
if(checkedValue)
{
$("#post_button").hide();
} else {
$("#post_button").show();
}
});

The above code is used to show / hide post button while clicking Press Enter to Send checkbox. If checkbox is selected, you need to hide the post button. If not then you need to show the post button.

Submit a form using Enter Key

The below code is used to submit a form using enter key. First we need to check the press enter to send value via checkbox. If checked, then we need to get the keycode for Enter key inorder to submit a form. Keycode for Enter key is 13

$('#form').keydown(function(e) {
var checkedValue = $('#press_to_enter:checked').val();
if(checkedValue)
{
//enter key
if (e.keyCode == 13) {
//submit form
submit_form();
}
}
});

Submit a form using Button Onclick

If press enter to send option is not selected, then we will submit a form using Post button onlick function using the below jquery code

$('#post_button').click(function() {
var checkedValue = $('#press_to_enter:checked').val();
if(!checkedValue)
{
submit_form();
}
});

jQuery code to submit a form

function submit_form() {
var box_height = $('#response_messages');
var msg = $("#message").val();
if(msg != '') {
$.ajax({
type: "POST",
url: "update.php",
data: 'msg='+msg,
cache: false,
success: function(html) {
$('#response_messages').append(html);
var height = box_height[0].scrollHeight;
box_height.scrollTop(height);
$("#message").val('');
}
});
return false;
} else {
alert("Message cannot be empty!");
return false;
}
}

Posts from jQuery

Please don’t forget to share and subscribe to latest updates of the blog.

Thanks!

You May Also Like

Never Miss Any Web Tutorials, Guides, Tips and Free eBooks

Join Our Community Of 50,000+ Web Lovers and get a weekly newsletter in your inbox

 

I hate spam too. Unsubscribe at any time.

4 thoughts on “Facebook Style Press Enter to Send Option in Message / Comment Box using jQuery”

  1. Add laga kar q zalil karte ho users ko sharamkaro yar …. ek to demo ka keh kar ke yahan pe click karein or jab demo ke page per user jata he to demo ki jagah per adds hoti he …. please feel some shame.

    Reply

Leave a Comment