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

Discover the method to retrieve every element from a Listbox with the click of a Button and utilizing an ajax call

How can I retrieve all the elements from a Listbox when a Button Click event triggers an ajax call? I have created a function that successfully returns all the elements from the Listbox. However, when I try to bind it with the ajax call, it doesn't w ...

Converting JQuery Object (Ajax-response) to an Array Containing Keys and Values

When I make an $.ajax request, the response I receive looks like this: https://i.sstatic.net/UfnfQ.jpg (please don't worry about the Russian symbols, they are just strings of text:)) I am aware that when PHP sends the request, it is in a simple arr ...

Pointer-events property in pseudo elements not functioning as expected in Firefox browser

I have a horizontal menu that includes mid-dots (inserted using the ::after pseudo element) to separate the menu items. I want to prevent these mid-dots from being clickable. This works fine in Safari, but in Firefox (v.47), the pointer-events: none prope ...

The dropdown feature in Materialize does not function properly when used within a dynamically generated card

Using the materialize dropdown example within a client-side html file and initializing it with jQuery is seamless: $('.dropdown-button').dropdown({ inDuration: 300, outDuration: 225, constrain_width: false, // Does not change w ...

Error occurred during download or resource does not meet image format requirements

Encountering an issue when attempting to utilize the icon specified in the Manifest: http://localhost:3000/logo192.png (Download error or invalid image resource) from the console? import React from 'react'; import Logo from '../Images/logo1 ...

- The click function is failing to work after an ajax call [Potential event delegation problem]

I have a webpage where I update the contents of an unordered list using $.get() every 5 seconds. The issue I am facing is that the click function for the list items is not working properly. Even though the list items are being updated correctly, there se ...

Leveraging AJAX and jQuery for data storage

Need a solution using AJAX and jQuery to save data from one form in another form while preserving the values. The stored information should be hidden from the front end user, with an option for the user to delete the data if desired. Retrieving the stored ...

Objective subject for an element within a :not operation

I have a function that specifically excludes a style on links by targeting their IDs. Each of my links has an ID, so I use that to exclude the style. a:not([id='hopscotch_logo'] { color: red; } Now, I also want to find links that are children o ...

detecting syntax errors in CSS with @media queries and keyframes

/*general CSS setting for all device types above hd*/ * { margin: 0; padding: 0; } #watchonly { display: none; } ...

What steps can I take to guarantee that both images and text adapt well to different screen sizes?

Is there a way I can organize my website to display 3 movies per row with the text centered relative to the image? Here is how it currently looks (the red box is just for reference, please ignore): https://i.stack.imgur.com/w2pgN.jpg Also, when I resize m ...

What is the best way to obtain a link within a function() { ...}?

I am unable to provide the entire code at this moment. Here's a snippet of jquery code $('#contentBox').hover( function() { posi("5",768,"box.jpg","i need link here","some text here"); } ...

Collapse all "Read More" buttons simultaneously using Bootstrap

I am attempting to design a segment that contains multiple paragraphs that can be expanded or collapsed individually. How can I achieve this using only pure bootstrap css so that they do not all expand and collapse simultaneously? #summary { font-size: ...

Press and hold feature using CSS or JavaScript

When working with a jQuery draggable element, my objective is to change the cursor to a move cursor when clicking and holding the header. I have attempted using CSS active and focus properties, but so far no changes are taking place. ...

Modify the database once authorized by the administrator

`I have a webpage that showcases testimonials. I am looking to only display the testimonials with a "status" of "1" in my database. How can I quickly update the "status" column from "0" to "1" right after the admin clicks on update? I am also incorporati ...

Interactive calendar feature with a popup that appears when hovering over an event

I am looking to create a popup on hover with full calendar functionality, similar to the one seen at this link. I have attempted using full calendar with qtip, but I was unable to achieve a clickable popup as it disappears when the mouse moves away. Here ...

I am struggling to make my table adapt to different screen sizes and become

Here is an example of a table: <TABLE class=vysledky > <TR class=podtrzeni> <TD width="39" height="19">Order <br /> League</TD> <TD width="39" height="19">Order <br /> Team</TD> <TD width="3 ...

I need help with creating an AJAX JSON call using Angular. Let me share the JavaScript function that I currently have

When a button is clicked, the function below is called. It retrieves data from a JSON file and stores it if a success message is received. Here is a screenshot of the returned data. My JavaScript function is working correctly, but I am new to Angular and l ...

Is it feasible to implement a jQuery dialog with an ASP.NET user control?

Having some trouble opening a user control in a jQuery dialog popup. It seems that none of the server-side events are being triggered, and I suspect that the UpdatePanels are not functioning either. Has anyone encountered this issue before? Is there a wor ...

Difficulties encountered with CSS transitions when using the background

I stumbled upon some interesting examples on Stack Overflow about the fade effect on link hover. Curious, I decided to try it out myself and created this JSFiddle. <div class="fade"/> .fade { -o-transition: 0.3s; -moz-transition: 0.3s; -khtml-tran ...

Set the position to fixed so it doesn't scroll

Is there a way to create a fixed position div that remains in place when the user scrolls, similar to the effect shown in this example image? Position Absolute: https://i.sstatic.net/4RAcc.png Position Fixed (desired effect): https://i.sstatic.net/3DIna. ...