1

I want to validate that atleast one checkbox is selected. The checkboxes are added dynamicly so the exact ID's are unknown. All i know is that they start with the same ID name e.g. "Sameid_xxx", "Sameid_xx1" ,"Sameid_xx2" etc..

here is what i have:

$cbx_group = $('input[Id^="Sameid"]'); 

$cbx_group.prop('required', true);
if ($cbx_group.is(":checked")) {
  $cbx_group.prop('required', false);
}

the problem here is that this makes all checkboxes required. I also dont have form validator

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Kimos
  • 99
  • 2
  • 9

3 Answers3

1

Use $cbx_group.is(":checked") like below:-

The below code will do two things:-

1.remove required from all check-boxes if any-one is checked.

2.Add required again back to all check-boxes when all check-boxes are un-checked.

Code:-

$cbx_group = $('input[Id^="Sameid"]'); 
$cbx_group.prop('required', true);
$cbx_group.on('click',function(){
  if($cbx_group.is(":checked")) {
    $cbx_group.prop('required', false);
  }else{
    $cbx_group.prop('required', true);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="Sameid_XXX">1<br>
<input type="checkbox" id="Sameid_XX1">2<br>
<input type="checkbox" id="Sameid_XX2">3<br>
<input type="checkbox" id="Sameid_XX3">4<br>

Reference taken:- https://stackoverflow.com/a/39849541/4248328

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
0

You can check the number of checkboxes checked using length

 if($cbx_group.is(":checked").length > 0))
 {
    $cbx_group.prop('required', false);
 }
adiga
  • 34,372
  • 9
  • 61
  • 83
0

You can try this:

Use attribute contains selector. Link: http://api.jquery.com/attribute-contains-selector/

function test() {
$cbx_group = $('input[Id*="Sameid"]');

$cbx_group.prop('required', true);
if ($cbx_group.is(":checked")) {
  $cbx_group.prop('required', false);
  console.log('checked');
} else {
console.log('not checked');
}

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="Sameid1">
<input type="checkbox" id="Sameid2">

<button id="one" onclick="test()">Click</button>
Pankaj Shukla
  • 2,657
  • 2
  • 11
  • 18