Fil Fil - 5 months ago 12
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.

html

<form action="http://website.com/transaction_items/add_comment" 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>
</span>
</div>
</form>


jQuery

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
submit.send(form_id);
});
}


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

nutshell

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

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