0

I have a jQuery Bootstrap Star Rating (http://plugins.krajee.com/star-rating). I am stuck trying to pass value it gets to Rails form_for. I do not know how to submit the form with value obtained from script.

<%= 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 that should trigger form submission:

<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); - Just checking if the data is entered. $("#rating_field").val(value); - Assigning value to the field. $("#my-form").submit(); - triggering a submit.

Thanks in advance!

3 Answers3

3

doing $("#my-form").submit(); will NOT submit the form remotely. Instead a full refresh will occur

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

is the rails way of doing it.

EDIT

rails-ujs has a convenient wrapper for this

form = document.querySelector('form');
Rails.fire(form, 'submit');
Tony Vincent
  • 13,354
  • 7
  • 49
  • 68
1
$('#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();
});
max
  • 96,212
  • 14
  • 104
  • 165
0

I got it to work by using the click() function on the submit button, not on the form.

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

or

$('#submit-button').click();
B Seven
  • 44,484
  • 66
  • 240
  • 385