1

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.

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

I created a button which is accessing the getAnswer() function. Why value[i].checked == true wouldn't work?
Please update your question to provide a minimal, reproducible example so we can see your code. You can also post a link to JSFiddle but please don't put code in Pastebin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.