Link to first question: Ruby on Rails and Jquery: trying to switch characters after submit
I asked this question yesterday, and got what I believe to be some helpful feedback, but now I am now lost as to what is going wrong. I'm trying to build a tic-tac-toe game in RoR, and at the moment I'm stuck at trying to switch players after the page is submitted.
jQuery:
$(document).ready(function(){
var currentPlayer = $(#table).data("current-player");
$(".square").click(function(){
// Gather the position that was clicked
var number = $(this).data("position");
// Locate the game form
var form = $("form");
// Locate the input field corresponding to that position
var input = $("input[data-position='" + number + "']");
// Set the value of that input field to "X" or "O"
input.val(currentPlayer);
// Submit the form
form.submit();
});
});
Ruby:
def update
@game = Game.find(params[:id])
@game.update(game_params)
switch_player
redirect_to @game
end
def switch_player
session[:current_player] = session[:current_player] == 'X' ? 'O' : 'X'
end
HTML form:
<%= nested_form_for @game do |f| %>
<%= f.fields_for :moves do |move_form| %>
<p id="table" data-current-player: <%=session[:current_player] %>>
<%= move_form.label :position %><br>
<%= move_form.text_field :player, data: {position: move_form.object.position} %>
<%= move_form.hidden_field :id %>
</p>
<% end %>
<input type="Submit">
<% end %>
HTML board (just the first position):
<div id="board" align = center>
<table>
<tr>
<td data-position="0" class="square <%= class_for_move(0)%>"></td>
class_for_move:
def class_for_move(number)
move = @game.moves.find_by(position: number)
player = move.player
player.downcase + '_move' unless player.blank?
end
With the var currentPlayer
in the jQuery code, the .click becomes unclickable. But with "X"(or "O", respectively), the click registers and is submitted correctly. But the way this is set up, I was under the impression that var currentPlayer
should be coming out as a string, which should allow this to be clickable.
Link to next question: jQuery click not registering which player is clicking. What am I missing?