brianfalah
brianfalah

Reputation: 191

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

i'm developing a Ruby On Rails 2.3.8 application and I would like to know how to submit a remote_form_for when users press the ENTER key within the textarea. I'm already doing the html replace from the controller's action, once the form is submitted.

Here is my code:

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

Here is the form code:

<% remote_form_for :post, PostComment.new, :url => save_outside_comment_path(post_id), :html => {:method => :put, :onsubmit => save_outside_comment_path(post_id)} do |f| %>
      <%= f.text_area :comment, :rows => 1, :id => "txtOutsideComment_#{post_id}", :class => "new-reply-text" %>
      <%#= f.submit 'Publish', :onClick => "javascript:return validateField(this, #{PostComment::OUTSIDE_COMMENT_MIN_LENGTH}, #{PostComment::OUTSIDE_COMMENT_MAX_LENGTH});" %>
<% end %>

Please help me! Thank you for reading

Upvotes: 0

Views: 2080

Answers (1)

ShankarSangoli
ShankarSangoli

Reputation: 69905

In your code this is pointing to the textbox so it will not work. Try this

jQuery('.new-reply-text').keypress(function(e) {
    if (e.keyCode == 13 && !e.shiftKey) {
        e.preventDefault();
        var frm = $(this).closest("form");  
        jQuery.ajax({
            url: frm.attr("action"),
            data: frm.serialize(),
            success: {},
            dataType: json
        });
    }
});

Upvotes: 2

Related Questions