claudios claudios - 8 months ago 24
jQuery Question

Calling a click function when pressing the Enter key

I've been having a hard time figuring out why keypress won't work. No, I mean it's working but the result returned is json. I wanted to return the html like when I press the Post button. How can I make the enter key and a button click functions the same? Thanks! This is my code so far.

Note: The code works fine after clicking the
post comment
but returns a json data if pressing


function commentApp(item_id){
$('.js-post-button').on('keypress click', function(e){
var url = $('form#js-post-comment').attr('action');
if (e.which === 13 || e.type === 'click') {
type : 'POST',
url : url,
dataType : 'json',
data : $('#js-post-comment').serialize(),
success : function(result) {

function showComments(item_id) {
var url = $('#js-comment').attr('data-url');
url : url+'/comments/'+item_id,
type : "POST",
dataType : "html",
success : function(result) {


$data = array(
'checklist_item_id' => $id,
'comment' => $this->input->post('comment'),
'date_posted' => date('Y-m-d h:i:s'),

echo json_encode($data);


<form id="js-post-comment" method="post" role="form" action="<?php echo site_url('document_items/add_comment/'.$value['checklist_item_id'])?>">
<div class="input-group">
<input id="js-input-comment" type="text" class="form-control" name="comment" placeholder="Write a comment...">
<span class="input-group-btn">
<button class="js-post-button btn btn-default" type="button">Comment</button>
</div><!-- /input-group -->


You should listen to submit event on the form:

$('#js-post-comment').on('submit', function(event) {
  event.preventDefault(); // stop form from making native submit

  var url = $(this).attr('action');
    type     : 'POST',
    url      : url,
    dataType : 'json',
    data     : $(this).serialize(),
    success  : function(result) {
      console.log('Do something with result:');