Why do my checkboxes refuse to respond separately?

I am currently experiencing an issue with the checkboxes in my JavaScript game. They do not respond to individual clicks as expected. Each time I log the output, I receive index 0 regardless of which box I click on. The checkboxes seem unresponsive but the level functions are working correctly.

    // JavaScript code for handling checkboxes and levels

    window.onload = function() {

      console.log('DOM is loaded');

      // Function to check all checkboxes
      fillAll = function() {
        for (var i = 0; i < 25; i++) {
          document.bulbform.elements[i].checked = 1;
        }
      };

      // Function to clear all checkboxes
      clearAll = function() {
        for (var i = 0; i < 25; i++) {
          document.bulbform.elements[i].checked = 0;
        }
      };

      // Functions for different game levels
      levelOne = function() {
        clearAll();
        document.bulbform.elements[10].checked = 1;
        document.bulbform.elements[12].checked = 1;
        document.bulbform.elements[14].checked = 1;
      };

      // Define other level functions here...

      // Check if all checkboxes are checked
      checkAll = function() {
        var win = 1;
        for (var i = 0; i < 25; i++) {
          if (document.bulbform.elements[i].checked == 1) {
            win = 0;
          }
        }
        if (win == 1) {
          alert("You Won!");
        }
      };

      // Function to toggle checkbox value
      check = function(v) {
        a = parseInt(v);

        if (document.bulbform.elements[v].checked == 1) {
          document.bulbform.elements[v].checked = 0;
        } else {
          document.bulbform.elements[v].checked = 1;
        }
        checkAll();
      };
    };
<body>
  <div class="row">
    <div class="col s12 m6">
      <div class="card-panel blue-grey lighten-3">
        <form name="bulbform">

          <!-- Checkbox inputs with labels -->
          <!-- Update values, IDs, and other attributes as needed -->

          <a href="javascript:levelOne()" class="waves-effect waves-teal btn-flat">Level 1</a>
          <a href="javascript:levelTwo()" class="waves-effect waves-teal btn-flat">Level 2</a>
          <a href="javascript:levelThree()" class="waves-effect waves-teal btn-flat">Level 3</a>
          <a href="javascript:levelFour()" class="waves-effect waves-teal btn-flat">Level 4</a>
          <a href="javascript:levelFive()" class="waves-effect waves-teal btn-flat">Level 5</a>
          
          <!-- Button to clear checkboxes -->
          <button class="btn waves-effect waves-light btn-large" type="reset" value="clear" name="action">Clear<i class="material-icons left">lightbulb_outline</i></button>
      
      </div>
    </div>
  </div>
  <script type="text/javascript" src="game.js"></script>
  </body>

Answer №1

Dai offers valuable advice, but the crux of your issue lies in this snippet:

... onclick="javascript:check(value)" ...

The absence of a global value variable results in passing undefined, which equates to 0. What you should be passing is the actual value of the checkbox:

... onclick="javascript:check(this.value) ...

Additionally:

checkboxes in my JS game isn't responding to individual clicks

This behavior occurs because of your code:

if (document.bulbform.elements[v].checked == 1) {
  document.bulbform.elements[v].checked = 0;
} else {
  document.bulbform.elements[v].checked = 1;
}

If an unchecked checkbox gets clicked, it becomes checked by the listener, and vice versa. This redundant toggling can be eliminated by removing the listener and allowing the checkbox to function independently.

Answer №2

Seems like there may be an error in your approach. 1) Initially, the checkbox is set to true by default. 2) When you click the checkbox, it toggles to false, but your code contains

if (document.bulbform.elements[v].checked == 1) {
          document.bulbform.elements[v].checked = 0;
        } else {
          document.bulbform.elements[v].checked = 1;
        }

This will change the checkbox back to true. Therefore, every time you try to click the checkbox, its state will always return false due to the change made by your code.

The solution would be to remove the above code from your script. This should resolve the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating the style of a CSS element using Python Selenium

Is it possible to change the css element style using Python Selenium during automation to increase the height of the page? The structure of the element in the HTML is as shown below: <div style="overflow-y:scroll;overflow-x:hidden;height:150px;&quo ...

The bottom section is impacted by the bootstrap class

Currently, I am in the process of designing the store page for my website and have encountered an issue. I implemented a search function for the site, which works well. However, on the search.php page where the items are displayed based on the search query ...

"(PHP)WordPress produces a dynamic menu that adapts to different screen sizes

I recently created a menu on my WordPress site [ and I'm facing an issue with making it display vertically in a responsive way. The code in header.php is as follows: <!-- header --> <header> <div class="overNavPanel"> ...

Is there a way to align the Material UI mobile menu to the left edge of the screen?

Need help with this UI issue: Currently working on designing a mobile web app using React and Material UI. I'm struggling to get the sidebar menu to start from the left edge of the screen, as it seems to have an unwanted margin preventing it. Any sug ...

Is it possible to incorporate a foreach loop while also implementing unique adjustments at specific locations within the code?

I have been searching for a solution to this problem on various forums, but I couldn't find one that fits my needs. My challenge is to create a foreach loop for 12 elements, with 3 of them having a different class applied to them. This is the code I ...

Using jQuery ajax links may either be effective or ineffective, depending on the scenario. At times

Can someone please assist me in understanding why an ajax link may or may not work when clicked? It seems to function intermittently. window.onload = function(){ function getXmlHttp(){ ...... // simply ajax } var contentContainer = ...

The error message received is: "mongoose TypeError: Schema is not defined as

Encountering a curious issue here. I have multiple mongoose models, and oddly enough, only one of them is throwing this error: TypeError: Schema is not a constructor This situation strikes me as quite odd because all my other schemas are functioning prop ...

Creating a unique, random output while maintaining a log of previous results

While working on a recent project, I found myself in need of a custom Javascript function that could generate random numbers within a specified range without any repetitions until all possibilities were exhausted. Since such a function didn't already ...

Obtain JSON information from a backend Node.js server and transfer it to the frontend HTML

I am currently facing an issue while trying to access JSON data and display it on the frontend screen. I have exported it in Node.js and attempted to import it into a script tag in HTML, but unfortunately, I am not able to retrieve the data. Is there a sol ...

Align the text to the right within a display flex container

Below is the code snippet: <div className="listContent"> <div> <div className="titleAndCounterBox"> <div className="headerListTitle">{list.name}</div><br /> <div ...

Controller experiencing issues with Ajax passing null value

My webpage features a dropdown menu with a list of ID's to choose from. When a customer selects an option, it should update the price total displayed on the page. To achieve this functionality, I'm working on implementing an AJAX call that will u ...

Transforming Form Input into Request Payload for an AJAX Call

I'm facing a challenge in submitting my form data through a POST AJAX request and haven't been able to come across any solutions so far. Due to the dynamic creation of the form based on database content, I can't simply fetch the values usin ...

Encountering a Node.js error when executing the JavaScript file

When I try to run my Node.js application using the command "node main.js" in the terminal, I encounter an error saying "Error: Cannot find module 'D:\nodeP\main.js'". This is confusing for me as I have set the environment variable path ...

Error: The function getAuth has not been defined - Firebase

I have included the code snippets from index.html and index.js for reference. The analytics functionality seems to be working fine, but I am facing an issue with authentication due to an error during testing. Thank you for your help. index.html <script ...

Customize your AppBar with Material UI and NProgress integration

Snippet of Code: <AppBar color='inherit' position='fixed'><AppBar> I'm currently working with material-ui and facing an issue where nprogress doesn't show up at the top in my Nextjs App when using it in conjunctio ...

"Unlocking the Power of jQuery: A Guide to Accessing XML Child

I'm struggling to extract the xml in its current format. While I can easily retrieve the InventoryResponse, I am facing difficulties when trying to access the child node a:Cost. Despite conducting research, I have been unable to find a solution that w ...

When incorporating a CDN in an HTML file, an error message may appear stating that browserRouter is not defined

I am attempting to create a single HTML page with React and React-router-dom. Initially, I used unpkg.com to import the necessary libraries, and I was able to load the page with basic React components. However, when I tried incorporating React-router-dom ...

Rendering data in React using the array indexRendering data in React

I'm encountering an issue in React JS where I need to display all data from a REST API with a numeric index. REST API: [ { "id": "1", "start_date": "2020-05-08 09:45:00", "end_date": "2020-05-08 10:00:00", "full_name": "mirza", "cust_full_name": "fu ...

Can the values in all fields of a JSON be combined or subtracted with those of another object containing the same fields?

I am currently working with a Mongoose.js schema that is structured as follows: { "City": String, "Year": String, "Population": Number, "Blah": Number, "Nested": { "Something": Number, "More stuff": Number } } Is there an efficient w ...

The value control input does not get properly updated by ngModelChange

Having difficulty updating an input as the user types. Trying to collect a code from the user that follows this format: 354e-fab4 (2 groups of 4 alphanumeric characters separated by '-'). The user should not need to type the '-', as it ...