Previous question/answer: jQuery .click function is not working without a string
I am trying to build a tic-tac-toe game through RoR/jQuery/HTML and I can't figure out why the players aren't being registered on the clicks. Previously I was unable to get the .val
to work at all because currentPlayer
wasn't a string. But now it is, only it is not showing up as either of the two choices. Not sure where the code is wrong.
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)
redirect_to @game
switch_player
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 table (first cell only):
<div id="board" align = center>
<table>
<tr>
<td data-position="0" class="square <%= class_for_move(0)%>"></td>
Ruby 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
I feel like, given what is there, it should be working. But when I run the page, and click on a cell, it submits with nothing inside. It comes out as <td data-position="0" class="square "></td>
when it should be <td data-position="0" class="square x_move"></td>
, or o_move.
I used console.log
on currentPlayer
and it is showing up as undefined.
Could it have something to do with this syntax:
data-current-player: <%=session[:current_player] %>
where it should bedata-current-player='<%=session[:current_player] %>'
?