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

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;
		}
}

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

Thanks!
View Live Demo & Download

If you enjoyed this article, Get email updates (It’s Free)
http://w3lessons.info/wp-content/uploads/2014/06/press_enter_to_send_jquery.gifhttp://w3lessons.info/wp-content/uploads/2014/06/press_enter_to_send_jquery-150x150.gifKarthikeyan KfacebookFreebiesjqueryfacebook,Jquery,new techniques,tips & tricks
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...