【问题标题】:How to trigger a form_for submit (rails) from jQuery?如何从 jQuery 触发 form_for 提交(rails)?
【发布时间】:2016-12-14 09:47:52
【问题描述】:

我有一个 jQuery Bootstrap 星级评分 (http://plugins.krajee.com/star-rating)。我被困在试图将它获得的价值传递给 Rails form_for。我不知道如何使用从脚本中获取的值提交表单。

<%= form_for @book.reader_books.build, id: "my-form", :html=> {:id => 'my-form'} do |f| %>
    <%= f.hidden_field :book_id, value: @book.id, :id=>"rating_field" %>     
      <div class="col-md-6 ratings">
        <div align="center"><%= @book.rating_average.to_i %></div>
        <input id="input-id" name="input-id">
      </div>
    <% end %>
  <% else %>
    <strong>Your rate:</strong>
    <%= @book.reader_books.find_by!(reader: current_reader).rating %>

应该触发表单提交的脚本:

<script type="text/javascript">
    $('#input-id').rating().on('rating.change', function(event, value, caption) {
        console.log(value);
        $("#rating_field").val(value);
        $("#my-form").submit();
    });
</script>

console.log(value); - 只是检查是否输入了数据。 $("#rating_field").val(value); - 将 value 分配给该字段。 $("#my-form").submit(); - 触发提交。

提前致谢!

【问题讨论】:

    标签: jquery ruby-on-rails forms twitter-bootstrap


    【解决方案1】:

    $("#my-form").submit();不会远程提交表单。而是会发生完全刷新

    $("#my-form").trigger('submit.rails');
    

    是rails的做法。

    编辑

    rails-ujs 有一个方便的包装器

    form = document.querySelector('form');
    Rails.fire(form, 'submit');
    

    【讨论】:

    • Uncaught ReferenceError: Rails is not defined
    【解决方案2】:
    $('#input-id').rating().on('rating.change', function(event, value, caption) {
        // traversing up the DOM is faster and avoids hardcoding an ID.
        var $form = $(event.target).parents('form');
        // You can get inputs by name from a form element without querying the DOM.
        $form[0]["reader_book[book_id]"].value = value;
        $form.submit();
    });
    

    【讨论】:

      【解决方案3】:

      我通过在提交按钮上使用click() 函数 让它工作,而不是在表单上。

      $('input[type="submit"]').click();
      

      $('#submit-button').click();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-05
        • 1970-01-01
        • 2013-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多