Assign a class to the checkbox of the first parent

I have a set of checkboxes generated using a for loop. I want the first checkbox to act as a parent, and all other checkboxes should act as children. When the parent checkbox is clicked, all child checkboxes should be checked.

Although I have code to achieve this functionality, it does not work as expected.

$('.checkbox-all-index-1').click(function () {
    if($(this).is(':checked')) {
        $('.checkbox-index').prop('checked', true);
    } else {
        $('.checkbox-index').prop('checked', false);
    }
});

Let's assume the HTML structure is as follows:

<input class="group-selector-subscriber checkbox-index" type="checkbox">
<input class="group-selector-subscriber checkbox-index" type="checkbox">
<input class="group-selector-subscriber checkbox-index" type="checkbox">
<input class="group-selector-subscriber checkbox-index" type="checkbox">

Now, I need to assign the checkbox-all-index-1 class to the first checkbox created in the loop.

All these checkboxes are dynamically created through a loop, so assigning the class to one affects all others. I only want it to apply to the first one.

Thank you!

Answer №1

Here's a way to do it:

$('.group-selector-subscriber:nth-child(1)').click(function () {
  $(this).addClass('checkbox-all-index-1');
  if($(this).is(':checked')) {
    $(this).siblings().prop('checked', true);
  }else{
    $(this).siblings().prop('checked', false);
    $(this).removeClass('checkbox-all-index-1');
  }
});
.checkbox-all-index-1{
  width: 20px;
  height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
</div>
<div>
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
</div>
<div>
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
</div>

Answer №2

Why not give this a try? Considering your inquiry,

Assign the class checkbox-all-index-1 to the first checkbox.

 
$('.group-selector-subscriber').click(function() {
  $('.group-selector-subscriber').first().addClass('checkbox-all-index-1')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="group-selector-subscriber checkbox-index" type="checkbox">
<input class="group-selector-subscriber checkbox-index" type="checkbox">
<input class="group-selector-subscriber checkbox-index" type="checkbox">
<input class="group-selector-subscriber checkbox-index" type="checkbox">

Answer №3

Check out this link.

$('.checkbox-all-index-1').on('change', function() {
    if($(this).is(':checked')) {
        $('.checkbox-index').prop('checked', true);
    } else {
        $('.checkbox-index').prop('checked', false);
    }
});

Answer №4

Here is a way to create a parent element and calculate the number of child elements:

$(".group-selector-subscriber:first").click(function(e)
{   
   if($(".group-selector-subscriber:first").is(":checked"))
   {
      $(".group-selector-subscriber").prop("checked",true)
   }
   else
   {
      $(".group-selector-subscriber").prop("checked",false)
   }
});

$(".group-selector-subscriber:not(:first)").click(function()
{
  if($('.group-selector-subscriber:not(:first):checked').length===$('.group-selector-subscriber:not(:first)').length)
  {
     $(".group-selector-subscriber:first").prop("checked",true);
  }
  else
  {
     $(".group-selector-subscriber:first").prop("checked",false);
  }
});
.group-selector-subscriber
{
  width:100%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="group-selector-subscriber checkbox-index" type="checkbox">
<input class="group-selector-subscriber checkbox-index" type="checkbox">
<input class="group-selector-subscriber checkbox-index" type="checkbox">
<input class="group-selector-subscriber checkbox-index" type="checkbox">

Answer №5

Give This a Try:

$(document).ready(function(){
  $('.group-selector-subscriber:nth-of-type(1)').change(function(){
    $(this).nextAll('.group-selector-subscriber').prop('checked',$(this).prop('checked'));
    $(this).toggleClass('checkbox-all-index-1',$(this).prop('checked'));
  })
})

$(document).ready(function(){
  $('.group-selector-subscriber:nth-of-type(1)').change(function(){
    $(this).nextAll('.group-selector-subscriber').prop('checked',$(this).prop('checked'));
    $(this).toggleClass('checkbox-all-index-1',$(this).prop('checked'));
  })
})
.checkbox-all-index-1 {
  width: 20px;
  height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<div>
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
</div>
<div>
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
</div> 

To see the effect on the first checkbox when any checkbox is changed, use this code:

$(document).ready(function(){

  $('.group-selector-subscriber:nth-of-type(1)').change(function(){
    $(this).nextAll('.group-selector-subscriber').prop('checked',$(this).prop('checked'));
    $(this).toggleClass('checkbox-all-index-1',$(this).prop('checked'));
  })

 $('.group-selector-subscriber').change(function(){
    var isCheck = true;
    $(this).closest('div').children('.group-selector-subscriber').not(':nth-of-type(1)').each(function(){
      if(!$(this).prop('checked'))
        isCheck = false;
    })
    $(this).closest('div').children('.group-selector-subscriber:nth-of-type(1)').toggleClass('checkbox-all-index-1',isCheck);
    $(this).closest('div').children('.group-selector-subscriber:nth-of-type(1)').prop('checked',isCheck);
  })

})

$(document).ready(function(){

  $('.group-selector-subscriber:nth-of-type(1)').change(function(){
    $(this).nextAll('.group-selector-subscriber').prop('checked',$(this).prop('checked'));
    $(this).toggleClass('checkbox-all-index-1',$(this).prop('checked'));
  })

 $('.group-selector-subscriber').change(function(){
    var isCheck = true;
    $(this).closest('div').children('.group-selector-subscriber').not(':nth-of-type(1)').each(function(){
      if(!$(this).prop('checked'))
        isCheck = false;
    })
    $(this).closest('div').children('.group-selector-subscriber:nth-of-type(1)').toggleClass('checkbox-all-index-1',isCheck);
    $(this).closest('div').children('.group-selector-subscriber:nth-of-type(1)').prop('checked',isCheck);
  })

})
.checkbox-all-index-1 {
  width: 20px;
  height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
<div>
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
</div>
<div>
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
  <input class="group-selector-subscriber checkbox-index" type="checkbox">
</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

The image is not properly aligned with the background image

I'm currently working on a page design using bootstrap and css where I want images to fade and reveal the background when hovered over. The challenge I'm facing is that although all images are set to 100px in size, there is white space visible ar ...

Fetch data dynamically upon scrolling using an AJAX request

Instead of making an ajax call to load data, I want to do it on scroll. Here is the code I have: $.ajax({ type: 'GET', url: url, data: { get_param: 'value' }, dataType: ' ...

How can I generate an Xpath for the given element?

I am trying to find the Xpath for the specific name (I1888 - Child 1.1) without using the contains function. Currently, I am using the following xpath: "//span[contains(@class,'TreeTitleRed')][contains(.,'Child 1.1')]", but I would like ...

How can jQuery verify if an input value is contained within an array?

I've been attempting to verify if the value of an input field is part of an array, but for some reason it's not working. Here is my approach: var postcode1 = []; for (var i = 21000; i < 21999; i++) { postcode1.push({ val: i, text ...

I seem to be having a problem with CSS and Flexbox sizing. Does anyone have an explanation for what might be

Hey there! I'm currently in the process of building a Netflix clone, and everything seems to be working well except for one issue with the layout. No matter how I adjust the width of the div containing the images, they just won't change size. I&a ...

Achieving a seamless blend of parent background with child background: A step-by

I am trying to make the parent background color overlap the child background color in two divs. Currently, the child's background is overlapping the parent's background. Please refer to the JS-Fiddle link below for more information: <div id=" ...

Modify a website link using Javascript by detecting two separate button clicks

I am seeking a way to dynamically change the src attribute of different images on a house depending on which button has been clicked. There are two groups of buttons: The types of house parts, such as windows, doors, garage, soffits, and gutters. The col ...

What is the method for combining two box geometries together?

I am looking to connect two Box Geometries together (shown in the image below) so that they can be dragged and rotated as one object. The code provided is for a drag-rotatable boxgeometry (var geometry1). What additional code do I need to include to join t ...

Using Javascript or jQuery, focus on a div containing a paragraph element with a particular text

I've been struggling for hours trying to figure out how to select a div that contains a specific p element. HTML <div class="NavBar_Row_Button2"><p>DONATE</p></div> <div class="NavBar_Row_Button2"><p>CONTACT</p ...

Exploring the functionalities of JSON and AJAX with a two-dimensional array

I have created a function to call JSON data, but it's not working. Any suggestions on how to properly call it? function fetchCompanyExpensesType(elementId){ $.ajax({ url: "../../modal/get_companyexpenses_type.php", dataType: ...

Challenges with the efficiency of hover effects

I have a div with a background image and inside that div, there is a component called Hero. I want to add a simple hover effect on a div with a className newBigButton. However, the transition is laggy when the background image is present. Here's the c ...

Flexbox: Distribute remaining space evenly while allowing content to wrap

Is there a method to instruct flexbox items to occupy the available space while wrapping as soon as they become smaller than their content? However, some items have a fixed width percentage. HTML <div class="grid"> <div class="grid__item"> ...

Is there a way to update my profile picture without having to constantly refresh the page after uploading it?

Here is the code for my profile page. I am considering using a callback along with another useEffect function, but I'm unsure. Please help me in finding a solution. For now, let's ignore all the code related to deleting, saving, and handling ingr ...

Jquery is not displaying the background color of the progress bar

Greetings to all! I am currently working on implementing a progress bar for my website, but I am encountering an issue where the background-color is not displaying correctly on scroll. I would greatly appreciate any assistance with this matter. Below you c ...

Determining the window height using jQuery when overflow is set to hidden

I've built a full screen web application that I don't want to scroll, so I used this code: $("body").css("overflow", "hidden"); However, after adding a resize listener: $(window).resize(function(){ console.log("Inner height: " + $(window). ...

Retrieve the background color using code-behind

Despite its humorous appearance, I am having trouble with the Syntax :( I have a background color in my code behind file and need to correct the syntax here so that my Table displays the correct background color: <Table style="background-color:" &apos ...

Is it not possible to collapse in webkit?

Check out this jsfiddle link for a visual example: http://jsfiddle.net/qrbhb/ If you use the following HTML markup: <div>There should be no gap between us</div> <br /> <div>There should be no gap between us</div> along with ...

Error message: "Invalid syntax detected while using the jQuery UI select plugin"

While utilizing jquery 1.8.1, I encountered a particular error message related to the jquery ui select plugin within the second code snippet. The specific error is shown below: Uncaught Error: Syntax error, unrecognized expression: li:not(.ui-selectmenu-g ...

Guide on converting HTML datetime picker datetime-local to moment format

I am looking to convert an input type : <input type="datetime-local" name="sdTime" id="stTimeID" onChange={this.stDateTime} /> into a specific date format: const dateFormat = 'MM/DD/YYYY hh:mm:ss a'; To achieve this, I need to transfer ...

Using Jquery to make an Ajax request to an Asp.net Web Method

My current approach involves using a jquery method to transmit only the member identification # from the client side to the server side. On the server side, I have a traditional Web Method in place to receive the data and execute SQL queries accordingly. ...