My Jquery CSS Checkbox is failing to register when it's checked

I have implemented custom checkboxes using a custom CSS checkbox generator.

$( ".button" ).click(function() {
  if(document.getElementById('terms_checkbox').checked) {
    alert('Checkbox is checked');
  } else {
    alert('Checkbox is not checked');
  }
 });
.button{
background:red;
width:200px
height:100px;
}

.control {
    font-family: arial;
    display: block;
    position: relative;
    padding-left: 30px;
    margin-bottom: 15px;
    padding-top: 3px;
    cursor: pointer;
    font-size: 16px;
}
    .control input {
        position: absolute;
        z-index: -1;
        opacity: 0;
    }
(control script and css code here)
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="control-group">
    <label class="control control-checkbox">
        First checkbox
            <input type="checkbox" />
        <div class="control_indicator"></div>
    </label>
</div>

<div class="button">
Click Me
</div>

After clicking the button, it fails to detect whether the checkbox is checked or not. What could be causing this issue?

Answer №1

Don't forget to include an id for your html <input/> tag in order for the JavaScript to work properly. It should look like this:

<input type="checkbox" id='terms_checkbox'/>

Feel free to try out the code snippet below.

$(document).ready(function() {
  $(".button").click(function() {
    if (document.getElementById('terms_checkbox').checked) {
      alert('I am checked');
    } else {
      alert('I am not checked');
    }
  });
})
.button {
  background: red;
  width: 200px height:100px;
}

.control {
  font-family: arial;
  display: block;
  position: relative;
  padding-left: 42px;
  margin-bottom: 15px;
  padding-top: 3px;
  cursor: pointer;
  font-size: 16px;
}

... (CSS code continues)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="control-group">
  <label class="control control-checkbox">
    First checkbox
    <input type="checkbox" id='terms_checkbox'/>
    <div class="control_indicator"></div>
  </label>
</div>

<div class="button">Click Me</div>

Make sure to wrap your JQuery code with $(document).ready to ensure that the content is fully loaded onto the DOM:

Answer №2

Make sure to pay attention to the details here. It seems like you forgot to select your checkbox element as there is no element with the id terms_checkbox. When using jQuery, it's recommended to utilize it for each selection instead of using plain JS/jQuery combination.

If you need to access the property checked, consider using prop(), attr(), or is().

$( ".button" ).click(function() {
  if($(".control-checkbox").find("input[type='checkbox']").prop("checked")) {
    alert('I am checked');
  } else {
    alert('I am not checked');
  }
 });
.button{
background:red;
width:200px
height:100px;
}

.control {
    font-family: arial;
    display: block;
    position: relative;
    padding-left: 30px;
    margin-bottom: 15px;
    padding-top: 3px;
    cursor: pointer;
    font-size: 16px;
}
    .control input {
        position: absolute;
        z-index: -1;
        opacity: 0;
    }
(control_indicator styling code omitted for brevity)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="control-group">
    <label class="control control-checkbox">
        First checkbox
            <input type="checkbox" />
        <div class="control_indicator"></div>
    </label>
</div>

<div class="button">
Click Me
</div>

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

What could be preventing my HTML replacement assignment from functioning properly?

Whenever a choice is made, I want to substitute the current content with different content. My current attempt is to update the content from "HuckFinn" to "Tom Sawyer will be added later" when the user selects "Tom Sawyer" from the drop-down menu. However, ...

Tips on passing data in complex formats to an MVC2 controller using JQuery (Ajax)

When sending a Jquery Json serialized object to my controller, I am facing an issue where not all of the data is being passed. Specifically, one of the members is a complex type that is also Json serialized, and this particular member, RoutingRuleModel, is ...

I am having trouble adding multiple items on different occasions - is it something to do with JQUERY

I have been working on a dynamic website that loads Firebase values into a table. However, I encountered an issue where the data does not appear when going back to the orders page after visiting another page. After some testing, I found that placing a but ...

The collapse component from bootstrap is not visible due to an overlapping button

I am currently working on a responsive calendar featuring full-width buttons for events, accompanied by additional information displayed using the collapse component below. However, I am facing an issue where the button overlaps with other elements, preven ...

Angular animation triggered when a specific condition is satisfied

I am working on an animation within my Angular application @Component({ selector: 'app-portfolio', templateUrl: 'portfolio.page.html', styleUrls: ['portfolio.page.scss'], animations: [ trigger('slideInOut&apo ...

saving user information with asynchronous HTTP calls

I am encountering an issue while trying to save my form data using AJAX. When I submit the form data in a JavaScript file that calls another PHP file to perform an insertion operation, an error occurs. Here is the code snippet: <button id="submit" cl ...

After refreshing the page, the jQuery AJAX item becomes unclickable

Currently utilizing Django Within the body block <div id="tag_like"> {% if liked %} <img id="unlike" title="unlike" src="{{ STATIC_URL }}pic/bad.png" /> {% else %} <img id="like" title="like" src="{{ STATIC_URL }}pic/go ...

What is the best way to create a fully clickable navbar item for the Bootstrap dropdown feature?

I'm struggling to make a button in a navbar fully clickable for the dropdown to open. Even when I try adding margin instead of padding, it only makes things worse. Can someone help me figure out what mistake I'm making here? Essentially, my goal ...

Determine the total by multiplying the value of a dropdown menu and a text input field using jQuery when the values are changed

I am new to jQuery and JavaScript. I have a textbox and a select box, and when I enter a value in the textbox and select a value from the select box, I want to display the multiplication of both values in another textbox. I have tried doing this with two t ...

Troubleshooting the fluid container problem in Bootstrap 3

I am currently working on a website using Bootstrap 3 framework. I have a specific section where I need to have two fluid containers placed side by side, each with different background colors. One of these containers should also include a background image ...

Apply a specific class to a list once scrolling beyond a certain offset of a group of division elements

I seem to be getting close, but I'm struggling to finalize this task. Essentially, as you scroll down to each image, the div containing that image's offset from the top of the window (with a buffer of -500) should add a .selected class to the cor ...

Creating an element in react-draggable with two sides bound and two sides open - here's how!

At the moment, I am facing an issue where the element is restricted from moving outside of the container with the class of card-width-height. My goal is to have the right and bottom sides bounded within the container while allowing the element to move beyo ...

Placing emphasis on a link's destination

Is there a way to automatically focus on an input field after clicking on a local href link? For example, I have the following: <a href="#bottom"> Sign up </a> And at the bottom of the page : <div id="bottom"> <input type="email" nam ...

Design an ARIA menu role with HTML and CSS code

Currently, my code is set up, but I'm unsure about integrating the tab/arrows to navigate to the sub-menu. You can view the code on jsfiddle: https://jsfiddle.net/Fep5Q/60/ This snippet shows a portion of the HTML code I've implemented: <di ...

Minimizing the menu bar while scrolling down (bootstrap3)

Could anyone help me with creating a navigation-bar effect similar to the one seen on ? I want the bar to shrink and the logo to change after scrolling down my page. My website is built using bootstrap 3. Is there a simple way to achieve this effect with ...

Div Randomly Transforms Its Vertical Position

After successfully creating a VS Code Extension for code completion, I decided to develop a website as a landing page where users can sign up and customize their extension settings. The editor I built pops up first on the page seemed to be working fine in ...

Updates in dropdown events when options data has been modified

Hey there, I'm wondering about dropdown events. Let's say I have two dropdowns. When a selection is made in the first dropdown, all options in the second dropdown are replaced with new ones. For example, let's say the first dropdown has thes ...

What is the best way to ensure all my borders are uniform in size?

As I work on a JavaScript project that organizes words into blocks based on their size, I encountered an issue with inconsistent border thickness in certain areas. I'm using spans to contain each word, but I can't figure out how to make the borde ...

Should I create CSS rules for different screen sizes or should I dynamically render components based on the screen size?

As I delve into learning React, I find myself unsure about the most effective approach to make websites responsive. Currently, I am utilizing Semantic UI React as my CSS Library. While everything displays perfectly on desktop, I encounter some issues when ...

Filtering images by their class using a drop-down menu allows for easier organization and sorting based

While browsing around, I came across another inquiry regarding filtering images by category using input form and jQuery. It was similar to what I am trying to achieve. I experimented with some JSFiddles but unfortunately had no luck. If you're curiou ...