claudios claudios - 6 months ago 11
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
button
but returns a json data if pressing
enter
key.


JS:

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') {
$.ajax({
type : 'POST',
url : url,
dataType : 'json',
data : $('#js-post-comment').serialize(),
success : function(result) {
$('#js-input-comment').val('');
showComments(item_id);
}
});
}
});
}

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


PHP:

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

$this->item_comments->insert($data);
echo json_encode($data);


HTML:

<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>
</span>
</div><!-- /input-group -->
</form>

Answer

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');
  $.ajax({
    type     : 'POST',
    url      : url,
    dataType : 'json',
    data     : $(this).serialize(),
    success  : function(result) {
      console.log('Do something with result:');
      console.log(result);
    }
  });
});
Comments