Skip to content
the poor coder

how get checkbox if checked in jquery

Poor Man
Published
Reading time
1 min read

How to Get Checkbox if Checked in jQuery#

If you want to get the value of a checkbox when it is checked using jQuery, you can use the following code:

JavaScript

$(document).ready(function(){
  $('#checkbox-id').change(function(){
    if(this.checked){
      var checkboxValue = $(this).val();
      console.log('Checkbox is checked and its value is ' + checkboxValue);
    }
  });
});

This code creates an event listener for the checkbox with the ID 'checkbox-id'. When the checkbox is changed (i.e. checked or unchecked), the function inside the change() method is executed. Inside this function, we check if the checkbox is checked using the 'this.checked' property. If it is checked, we get the value of the checkbox using the 'val()' method and store it in a variable called 'checkboxValue'. Finally, we log a message to the console that includes the value of the checked checkbox.

If you have multiple checkboxes, you can use a class selector instead of an ID selector to target all of them, like this:

JavaScript

$(document).ready(function(){
  $('.checkbox-class').change(function(){
    if(this.checked){
      var checkboxValue = $(this).val();
      console.log('Checkbox is checked and its value is ' + checkboxValue);
    }
  });
});

This code is similar to the previous example, but instead of targeting a specific checkbox by ID, we're targeting all checkboxes with a class of 'checkbox-class'. When one of these checkboxes is checked, the function inside the change() method is executed and we get the value of that checkbox.

Overall, getting the value of a checked checkbox in jQuery is a simple process that can be accomplished using the 'change()' method and the 'val()' method.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC