Creating Multible IDs for multible Buttons in one <Input> Tag
I'm working on a TicTacToe game using Django/Djangotemplates, Python and a bit Javascript. I've come across a problem tho. i only have one Button which is for-looped 9 times. its ID is its index. Now I'm not certain how to add the {{index}} which i defined in the for loop in the javascript onclick function.
here the html template
<div class="grid-container">
{% for index in object.board %}
<div class="grid-item">
<input onclick="change(button.id)" class="buttonsize btn-outline-purple" type="submit" value="" name="button" id="{{index}}">
</div>
{% endfor %}
</div>
</div>
</article>
</form>
<script>
function change(inputid){
console.log("test")
var elem = document.getElementById(inputid);
if (elem.value=="") elem.value = "X"
}
</script>
here the models.py
class TicTacToe(models.Model):
player1 = models.ForeignKey(User, on_delete=models.CASCADE, default="X", related_name="tictactoe_as_player1")
player2 = models.ForeignKey(User, on_delete=models.CASCADE, default="O", related_name="tictactoe_as_player2")
current_player = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tictactoe_current_player")
title = models.CharField(max_length=100)
board = models.CharField(max_length=9, default="012345678")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('tictactoe-detail', kwargs={'pk': self.pk})
and here the views.py
class TicTacToeCreateView(LoginRequiredMixin, CreateView):
model = TicTacToe
template_name = 'website/newgame_form.html'
fields = ['player1', 'player2', 'current_player', 'title', 'board']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class TicTacToeDetailView(UpdateView):
model = TicTacToe
fields = ['player1', 'player2', 'current_player', 'title', 'board']
def clean(self):
if 'button0' in self.data:
print('button0')
i also got a database but there is really not much in there except the player IDs
Adding index to the onclick should be OK
<input onclick="change({{index}})" class="buttonsize btn-outline-purple" type="submit" value="" name="button" id="{{index}}">