How to submit an AJAX form using the ENTER key from a text box?

I am developing a Ruby On Rails 2.3.8 application, and I would like to know how to submit a form remote_form_forwhen users press the ENTER key in a text box.

Here is the form code:

  <% remote_form_for :post, PostComment.new, :url => save_outside_comment_path(post_id), :html => { :method => :put} do |f| %>
     <%= f.text_area :comment, :rows => 1, :id => "txtOutsideComment_#{post_id}", :class => "new-reply-text" %>
  <% end %>

Here is a jQuery function that does submit but not AJAX:

jQuery('.new-reply-text').keypress(function(e) {
    if (e.keyCode == 13 && !e.shiftKey) {
        e.preventDefault();
        this.form.submit();
    }
});

I am already updating the page from my controller, do I want to specify any syntax, for example success:, from this jQuery function. I just want it to send remote_form_forusing AJAX.

+5
source share
1 answer

I think you are asking how to make an AJAX request instead of a full page view. If so

jQuery('.new-reply-text').keypress(function(e) {
  if (e.keyCode == 13 && !e.shiftKey) {
    e.preventDefault();
    jQuery.ajax({
      url: "/my/URL",
      data: jQuery(this).form.serialize(),
      success: function(){},
      dataType: "json"
    });
  }
});

, .get http://api.jquery.com/jQuery.get/

.post http://api.jquery.com/jQuery.post/

.ajax http://api.jquery.com/jQuery.ajax/

, /id jQuery, remote_form_for

+6

All Articles