Fil Fil - 1 year ago 73
jQuery Question

How to submit form data in ajax using enter in the keyboard

I am creating a comment functionality and below are my code so far.


<form action="" class="" id="form-comment" role="form" method="post" accept-charset="utf-8">
<input type="hidden" name="checklists_item_id" value="6" style="display:none;">
<input type="hidden" name="user_id" value="1" style="display:none;">
<div class="input-group col-xs-12">
<input type="text" name="comment" value="" class="form-control" id="comment-input" placeholder="Enter your comments..">
<span class="input-group-btn">
<button class="btn btn-default" id="doc-comment" type="button">Post</button>


This function is called when document is ready.

function comment () {
$('#doc-comment').click(function (e) {
var form_id = '#' + $(this).parents('form').attr('id');

// submit data from the form

The problem:

Using the button
<button class="btn btn-default" id="doc-comment" type="button">Post</button>
to submit data work fine, but
if I use enter in the keyboard, submit.send(form_id); will not do its function, instead the default form submission will execute.

How can I use ajax if use enter in the keyboard to submit form data?

Answer Source


$("#form-comment").on('submit', function(evt) {
    //  do your ajax stuff here

you can then toss the onclick button listener.. as this will handle the button submit as well

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download