This is my JavaScript:
function showQuestion(id) {
$(".question").hide();
$("#"+id).show();
}
$(document).ready(function() {
current_question=1;
showQuestion(current_question);
$("#next_question").click(function(){
alert('The current question is '+current_question);
current_question=current_question+1;
showQuestion(current_question);
});
$("#prev_question").click(function(){
alert('The current question is '+current_question);
current_question=current_question-1;
showQuestion(current_question);
});
});
And this is my show.html.erb [my Rails view]:
<div id="questions">
<% @questions.each_with_index do |q,i| %>
<div id="<%= i + 1 %>" class="question">
<strong><%= q.body %></strong>
<% if q.type == "MultipleChoice" %>
<% q.choices.each do |choice| %>
<br /><%= radio_button_tag "question#{q.id.to_s}", "choice#{choice.id}", @answer == choice %> <%= choice.body %>
<% end %>
<% end %>
<table>
<tr><td><%= link_to "< Previous", '#', :remote => true, :id => "prev_question" %></td><td><%= link_to "Next >", '#', :remote => true, :id => "next_question" %></td></tr>
</table>
</div>
<% end %>
</div>
So, when I click the ‘Next’ or ‘Previous’ button, it works. But after that, neither button works. I have a feeling it has something to do with jQuery not working. Thanks!
You are really close!
The problem is that you are generating a set of links for each question with the same IDs, which isn’t correct. It sounds like the first set of links is being hidden when you click one of them the first time.
One solution is to move the table with the Previous and Next links outside of the tag that contains it. Here’s a fiddle showing a dumbed-down version of your code with prev and next links outside of the question div. http://jsfiddle.net/QNLF9/
You could also leave the links inside the question div, assign them a class and use a class selector in your jQuery code. Here’s an example. http://jsfiddle.net/traDx/
I hope that helps. One other little thing. You should use html escape codes
<and>instead of<and>respectively. Happy coding!