pixie123
pixie123

Reputation: 979

Get all checkboxes and check them by previous sibling

I have a code like this:

<div class="elements" id="elements">
    <span>
        <span>Check anyone (required)</span>
    </span>
    <input type="checkbox" name="vehicle" value="minivan"> Minivan
    <input type="checkbox" name="vehicle" value="car"> Car
    <input type="checkbox" name="vehicle" value="boat"> Boat

    <span>
        <span>Check anyone</span>
    </span>
    <input type="checkbox" name="sport" value="basketball"> Basketball
    <input type="checkbox" name="sport" value="soccer"> Soccer
    <input type="checkbox" name="sport" value="tennis"> Tennis
</div>

<button id="check">Check</button>

<script>
    document.getElementById("check").onclick = function () {
        // Check it all... if required text is found and at least one checkbox is not found for that specific checkbox name, then throw alert
    }
</script>

I want to check all checkboxes in the div class/id elements and then check the previous span span tag and if there is a "required" text, then make sure one at least one checkbox is selected.

For example, let's start with checkbox name="vehicle". We reference/look back in the previous sibling <span><span> and we see if the text "required" exists. If it does exist, we need to make sure at least checkbox of name=vehicle is checked. If not, we need to `alert('error! please check a checkbox');

For example in name="sport", we do not have to check if at least one checkbox is checked because the text "required" does not exist in previous span span.

I know its weird but it has to be like this - just need to work with it. any help? thanks everyone!

Upvotes: 0

Views: 409

Answers (3)

ni3solanki
ni3solanki

Reputation: 522

Try this one, will work as you want

$('document').ready(function()
{
	$(document).on("click", '#check', function(e){ 

        var parent_vdiv = $(".vehicle").parent('div').attr('id');
        if(parent_vdiv=="required"){
            var IsCheckedVehicle = $('input[name="vehicle[]"]:checked').length > 0;
            if(!IsCheckedVehicle){
                alert('Please select Vehicle atleast one');
                return false;
            }
        }
        var parent_sdiv = $(".sport").parent('div').attr('id');
        if(parent_sdiv=="required"){
            var IsCheckedSport = $('input[name="sport[]"]:checked').length > 0;
            if(!IsCheckedSport){
                alert('Please select Sport atleast one');
                return false;
            }
        }

       
        $(".vehicle").prop('checked', true);
        $(".sport").prop('checked', true);
        return true;
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="elements" id="elements">
    <span>
        <span>Check anyone (required)</span>
    </span>
    <div id="required">
        <input type="checkbox" name="vehicle[]" class="vehicle" value="minivan"> Minivan
        <input type="checkbox" name="vehicle[]" class="vehicle" value="car"> Car
        <input type="checkbox" name="vehicle[]" class="vehicle" value="boat"> Boat
    </div>
   

    <span>
        <span>Check anyone</span>
    </span>
    <div id="not_required">
    <input type="checkbox" name="sport[]" class="sport" value="basketball"> Basketball
    <input type="checkbox" name="sport[]" class="sport" value="soccer"> Soccer
    <input type="checkbox" name="sport[]" class="sport" value="tennis"> Tennis
    </div>
</div>

<button id="check">Check</button>

Upvotes: 0

Evgeny Melnikov
Evgeny Melnikov

Reputation: 1092

This could be the solution for you. I changed the HTML markup a little in order to have ability to get group easily.

// Checks whether required group has any checked checkbox
function checkAnyChecked(groupEl) {
  if (!groupEl.classList.contains('required')) {
    return true;
  }
  
  const checkboxes = groupEl.querySelectorAll('input[type="checkbox"]');
    
  for (let checkbox of checkboxes) {
    if (checkbox.checked) {
      return true;
    }
  }
  
  return false;
}


const groups = document.querySelectorAll('.group');

for (let group of groups) {
  if (!checkAnyChecked(group)) {
    console.log('Alert! Group not filled!', group);
  }
}
<div class="elements" id="elements">
    <div class="group required">
      <span>Check anyone (required)</span>
      <input type="checkbox" name="vehicle" value="minivan"> Minivan
      <input type="checkbox" name="vehicle" value="car"> Car
      <input type="checkbox" name="vehicle" value="boat"> Boat
    </div>

    <div class="group">
      <span>Check anyone</span>
      <input type="checkbox" name="sport" value="basketball"> Basketball
      <input type="checkbox" name="sport" value="soccer"> Soccer
      <input type="checkbox" name="sport" value="tennis"> Tennis
    </div>
</div>

<button id="check">Check</button>

Upvotes: 0

Jitan Gupta
Jitan Gupta

Reputation: 484

arrange you code as below:

<div class="elements" id="elements">
<div class="vehicle">
    <span>
        <span>Check anyone (required)</span>
    </span>
    <input type="checkbox" name="vehicle" value="minivan"> Minivan
    <input type="checkbox" name="vehicle" value="car"> Car
    <input type="checkbox" name="vehicle" value="boat"> Boat
</div>
<div class="sport">
    <span>
        <span>Check anyone</span>
    </span>
    <input type="checkbox" name="sport" value="basketball"> Basketball
    <input type="checkbox" name="sport" value="soccer"> Soccer
    <input type="checkbox" name="sport" value="tennis"> Tennis
</div>
</div>

and if you are using jQuery then

$('input[type=checkbox][name="vehicle"]').each(function(key,item){
 if($(item).prop('checked')){
    console.log('this one is checked'+item);
 }  
});

Note: change your button as below

<button id="check" type="button">Check</button>

if is inside a form tag else it will make post back request, as default button behaviour is type="submit".

Upvotes: 0

Related Questions