Question

I am new to Rails and working on a quiz application, and am having trouble implementing the timer properly. When a user creates a new quiz, the controller calculates the time they are given based on the number of questions, 1 minute per question, and this is value is stored in the database. The user is then redirected to the first quiz question and the timer starts. They can choose a multiple choice answer, then click "Next" to go to the next question. The problem is that the page for the next question loads and the timer starts over instead of continuing where it left off on the previous page.

The timer is in javascript. It is implemented in my view as a div:

    <%= content_tag "div", class: "timer", data: {time: @time} do %><% end %>

I can access the current time in my .js.coffee file (such as when "Next" is clicked) with

    $(".timer").countdown("getTimes")

How can I send this time value to the Rails controller / database since it is a javascript/jQuery object?

Or should I try a different approach altogether?

Thanks!

Was it helpful?

Solution

You can store the value returned by the JS timer code in an hidden html input field and retrieve that value as form variable when the form is submitted.

For more info on hidden inputs: http://webdesign.about.com/od/htmltags/p/input-hidden-tag.htm

OTHER TIPS

As per DevDude's guidance, a hidden input field worked to solve this.

My view has the timer in the "content_tag" The hidden input is placed in the form. The submit buttons are given a class of "nav-time" to call in coffeescript. show.html.erb

<%= content_tag "div", class: "timer", data: {time: @time} do %><% end %>

<%= form_tag . . . %>
.
.
<input type="hidden" name="time-submitted" value="">
.
.
<%= submit_tag "Next", class: "nav-time"%>
<%end%>

The coffeescript updates the value of the hidden field.

timed_test.js.coffee

jQuery ->
  $('.nav-time').on 'click', (event) ->
    times = $(".timer").countdown("getTimes")
    $('input[name="time-submitted"]').val(times)

The time is passed to the controller through the params[time-submitted], and the database is updated. When the next page, is rendered, the time is where it left off on the previous page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top