Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit an AJAX form with ENTER key, from textarea?

I'm developing a Ruby On Rails 2.3.8 application and I would like to know how to submit a remote_form_for form when users press the ENTER key within the textarea.

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 the jQuery function that does a submit, but not AJAX:

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

I already do the page update from my controller, do I don't want to specify any syntax like success: from this jQuery function. I just want it to submit the remote_form_for using AJAX.

like image 620
brianfalah Avatar asked Jun 15 '11 13:06

brianfalah


1 Answers

I think you're asking how to do an AJAX request instead of a full page submit. 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"
    });
  }
});

You can save a few parameters if you use .get http://api.jquery.com/jQuery.get/

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

Which are wrappers for .ajax http://api.jquery.com/jQuery.ajax/

I'm not a rails guy so you'll need to update the class/id of the first jQuery object to find the remote_form_for

like image 140
Brombomb Avatar answered Nov 11 '22 05:11

Brombomb