开发者

Rails 3 / jquery / ajax - can i change this to submit one answer instead of the entire form?

开发者 https://www.devze.com 2023-03-09 23:03 出处:网络
I\'m grateful to the folks who helped me meander my way through a diagnostic process here. I rewrote the code that i am hoping will continue to work through future versions of jQuery.

I'm grateful to the folks who helped me meander my way through a diagnostic process here. I rewrote the code that i am hoping will continue to work through future versions of jQuery.

I am concerned, though, about two things:

  1. Have i coded something else that is going to come back and bite me in the tail?
  2. Quite a few clients complete part of the questions, close the browser and expect their work to be there when they came back to finish. So the entire form is submitted every time a radio button is clicked (100+ records). I wondered about the possibility of creating a form for each question here and received no responses. Is there some way to submit one answer at 开发者_高级运维a time instead of the whole form?

view:

    <%= form_tag update_result_answers_path, :remote => true do %>
    <% @answers.each do |q| %>
        <tr>
            <td><%= q[0].question %></td>
            <% [ 1, 2, 3, 4, 5 ].each do |f| %>
                <% if f == q[1].score
                    chk="checked='checked'"
                else
                    chk=""
                end %>
                <td>
                    <input "<%= chk %>" class="submittable" name="answer[<%=q[1].id%>]" type="radio" value="<%= f %>" />
                </td>
            <% end %>
        </tr>
    <% end %>
    <% end %>

application.js:

$('.submittable').live('change', function() {
        $(this).parents('form:first').submit();
        return false;
        }
    );

controller:

  def update_result
    params[:answer].each_pair do |key,value|
      @ans = Answer.find(key.to_i)
      @ans.update_attributes(:score => value)
    end
  end

_index.js.erb:

$("#answers").html("<%=escape_javascript(render(@answers)) %>");

Thank you!


I would keep your view as it is, and change the application.js, to be as little obtrusive as possible :

$('.submittable').live('change', function() {
  $.post(
    $(this).closest('form').attr('href'),
    $(this).serialize()
  );
});

EDIT : I didn't see that you want to render the answers afterwards. I'm not sure how to avoid code duplication with this solution then...

0

精彩评论

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

关注公众号