Reputation: 86
I am starting to learn a bit of JavaScript. I am trying to create, let's say, some sort of a little game.
I have a matrix n * n matrix
which consists of CHECKBOXES. If a certain set of CHECKBOXES is set to TRUE, output whatever (not strongly defined).
My issue is that when I set which checkboxes will be set to true, nothing happens.
Here is part of the code where I create a "starting point" for the matrix:
for (var i = 0; i < matrix * matrix; i++)
{
values[i] = "values" + i;
}
Now here is the part where I give the checkbox type to every single element in that array:
for (var i = 0; i < matrix * matrix; i++)
{
var checkbox = "<input type = 'checkbox' value = '" + values[i].checked + "' />";
document.write(checkbox + values[i]);
if (i % 2 != 0)
{
document.write("<br>");
}
}
I know this won't work for matrices bigger than 2, but I wanna get a feel for smaller inputs first and work my way up.
Finally, this is part of the code where I check if certain boxes are set to true:
if (values[1] == true && values[3] == true)
{
document.write("You got it!"); // This doesn't get outputted :(
}
Here is the full code: https://pastebin.com/30Neb3zJ
I am really new to JS and any type of feedback/info would be appreciated.
Upvotes: 1
Views: 79
Reputation: 9273
There are several problems with your code:
All of the values in the values
matrix look like strings, e.g. values0
, values1
, etc. When you test if (values[1] == true && values[3] == true)
, you are testing whether a string value (e.g. values1
) is equal to the Boolean value true
.
You're testing the values of an array which never change. I think you want to test the contents of the actual checkboxes. To do that you'll need to retrieve those DOM elements and test whether their .checked
property is true
:
You're testing the values immediately when the page loads, rather than after the user checks some checkboxes. You'll need to call getAnswer()
after the user checks some boxes, or possibly every time they check a box.
So to test the checkboxes, and do it after the user has finished checking, you need to add an event listener to all of the checkboxes (or to a "submit" button of some sort, depending on what you want to trigger the test).
Upvotes: 1