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 Answers 3

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');
Sign up to request clarification or add additional context in comments.

1 Comment

Uncaught ReferenceError: Rails is not defined
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();
});

Comments

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.