开发者

Multiple forms using Rails & jQuery & AJAX

I have multiple coupons on a page and I'm trying to get comments to work on each coupon. So for each coupon i have a comments form. Im using jQuery + Ajax to accomplish this. Here's what my code looks like.

Coupon Page

 <p>Comments:</p>
  <% form_for(@comment) do |f| %>
    <%= f.label :body %><br /><%= f.text_field :body, :size => "24"  %>
    <%= f.hidden_field :coupon_id, :value => coupon.id %>
    <%= f.submit "Save" %> 
  <% end %>

Application.js

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setR开发者_如何转开发equestHeader("Accept", "text/javascript")}
})




jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

$(document).ready(function() {
  $("#new_comment").submitWithAjax();
})

I tried changing the jQuery selector to a class

$(".new_comment").submitWithAjax();

Thinking that would work, now all the submit buttons work, however it posts only the first form on the page.

What can I change to make it so ajax submits the correct form and not the first one?

This is what the rendered html looks like:

<form action="/comments" class="new_comment" id="new_comment" method="post">
  <div style="margin:0;padding:0;display:inline">
    <input name="authenticity_token" type="hidden" value="b2ToPsRqJ+aXvh/W1pCpWrOlX010aruhku7alWoUSSg=" /></div> 
    <table> 
      <tr> 
        <td width="260px"> 
          <label for="comment_body">Body</label><br />
          <input id="comment_body" name="comment[body]" size="24" type="text" />
        </td> 
      </tr>
    </table> 
  <input id="comment_coupon_id" name="comment[coupon_id]" type="hidden" value="1790" /> 
  <input id="comment_submit" name="commit" type="submit" value="Save" />
</form>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜