开发者

Using enter to submit a content in a textarea via ajax in rails3.1rc5

I have rails app with a textarea form like

<%= form_for Comment.new, :remote => true do |f| %>
<%= f.text_area :comment %>
<% end %>

and my javascript code is as follows

<script>
$(function(){
    $('textarea').keypress(function(e) {
        if (e.keyCode == 13 && !e.shiftKey) {
            e.preventDefault();
            var frm = this.form.submit();
            $.ajax({
                url: frm.attr(),
                data: frm.serialize(),
                success: {},
                dataType: json
            });
        }
    });

});

<开发者_如何学C/script>

the problem here is that the form gets submitted when the enter key is triggered but it does not render an ajax request instead the form is submitted via http request. Any help here thanks


If you need both to submit form and send ajax request, you should submit from after ajax request has been executed. So, you shoud either make ajax request syncronous or submit for in the ajax callback function.

If you don't need form to be submitted, use this

var frm=$(this).parent(); //if textarea tag directly in the from tag

because this code this.form.submit(); submits the form.

UPD

    $(function(){
        $('textarea').keypress(function(e) {
            if (e.keyCode == 13 && !e.shiftKey) {
                e.preventDefault();
//                var frm = this.form.submit(); <- this code submits the form immediately
                  var frm = $(this).parent(); // depends on form structute
                $.ajax({
                    url: frm.attr('action'),
                    data: frm.serialize(),
                    complete: function(){
                        frm.submit(); // if you need to submit form after ajax request has been completed, I think it is useless
                    },
                    dataType: json
                });
            }
        });

    });


1) You're submitting the form yourself, so it's no wonder it gets submitted

2) Your frm variable is incorrect, I think. You're setting it the the returned value of submit (which you shouldn't call anyway).

Try

$(function(){
    $('textarea').keypress(function(e) {
        if (e.keyCode == 13 && !e.shiftKey) {
            e.preventDefault();
            var frm = this.form; // don't submit the form yet
            $.ajax({
                url: $(frm).attr('action'), // remember to specify which attribute you want
                data: $(frm).serialize(),
                dataType: "json",
                success: function() { frm.submit(); } // submit the form when the ajax request is complete
            });
        }
    });

});

Here's a jsfiddle: http://jsfiddle.net/5yQjA/
The fiddle logs the various things that should occur in an element below the textarea, but that's just for testing - remove it in your version. Also, remember to uncomment the frm.submit() line

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜